#include "ESP8266WiFi.h"
#include "PubSubClient.h"
#include <OneWire.h>
#include <DallasTemperature.h>
#define SensorPin A0 // контакт для датчика влажности
#define ONE_WIRE_BUS 0 // Пин подключения OneWire шины, 0 (D3)
#define MIN 300 // значение полного полива
#define MAX 700 // значение критической сухости
float tempC = 0;
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
// WiFi
const char* ssid = "wifi_ssid";
const char* wifi_password = "wifi_password";
// MQTT
const char* mqtt_server = "192.168.0.100";
const char* plant_temp = "plant01/temp";
const char* plant_hum = "plant01/hum";
const char* mqtt_username = "user";
const char* mqtt_password = "user";
const char* clientID = "client_ESP8266_2";
// Initialise the WiFi and MQTT Client objects
WiFiClient wifiClient;
PubSubClient client(mqtt_server, 1883, wifiClient); // 1883 is the listener port for the Broker
void connect_MQTT(){
Serial.print("Connecting to ");
Serial.println(ssid);
// Connect to the WiFi
WiFi.begin(ssid, wifi_password);
// Wait until the connection has been confirmed before continuing
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Debugging - Output the IP Address of the ESP8266
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Connect to MQTT Broker
// client.connect returns a boolean value to let us know if the connection was successful.
// If the connection is failing, make sure you are using the correct MQTT Username and Password (Setup Earlier in the Instructable)
if (client.connect(clientID, mqtt_username, mqtt_password)) {
Serial.println("Connected to MQTT Broker!");
}
else {
Serial.println("Connection to MQTT Broker failed...");
}
}
void setup() {
Serial.begin(9600);
DS18B20.begin();
connect_MQTT();
Serial.setTimeout(2000);
DS18B20.requestTemperatures();
tempC = DS18B20.getTempCByIndex(0); // Замеры температур с DS18B20
delay(50);// Необязательная задержка
float sensorValue = analogRead(SensorPin);
// масштабируем значение в проценты
//int wil = map(sensorValue,MIN,MAX, 100, 20);
Serial.println(sensorValue);
Serial.println(tempC);
// PUBLISH to the MQTT Broker
if (client.publish(plant_hum, String(sensorValue).c_str()),(plant_temp , tempC))
{
Serial.println("Moisture sent!");
Serial.println(sensorValue);
Serial.println(tempC);
}
// Again, client.publish will return a boolean value depending on whether it succeded or not.
// If the message failed to send, we will try again, as the connection may have broken.
else {
Serial.println("Moisture failed to send. Reconnecting to MQTT Broker and trying again");
client.connect(clientID, mqtt_username, mqtt_password);
delay(10); // This delay ensures that client.publish doesn't clash with the client.connect call
client.publish(plant_hum, String(sensorValue).c_str()),(plant_temp , tempC);
}
delay(1000);
ESP.deepSleep(0.2*60e6);
}
void loop() {
}