У меня есть плата ESP32 с 2 реле и датчиком DHT22 и нижеуказанный код в Arduino, работающий на ESP32
MQTT Broker работает на Pi4 с москитом и красной панелью приборов.
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHTTYPE DHT22
const char* ssid = "MY SSID";
const char* password = "1234";
const char* mqtt_server = "192.168.1.118";
WiFiClient espClient;
PubSubClient client(espClient);
const int DHTPin = 14;
const int lamp = 25;
const int lamp1 = 26;
DHT dht(DHTPin, DHTTYPE);
long now = millis();
long lastMeasure = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
delay(1000);
WiFi.disconnect();
delay(1000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
String message;
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
char c = (char)payload[i];
message += c;
}
Serial.println();
if ((char)payload[0] == '0' || message == "false") {
digitalWrite(lamp, HIGH);
delay(100);
digitalWrite(lamp1, LOW);
Serial.println("lamp, HIGH si lamp1, LOW");
} else if ((char)payload[0] == '1' || message == "true") {
digitalWrite(lamp1, HIGH);
delay(100);
digitalWrite(lamp, LOW);
Serial.println("lamp, LOW si lamp1, HIGH");
} else if ((char)payload[0] == '2') {
digitalWrite(lamp, HIGH);
digitalWrite(lamp1, HIGH);
Serial.println("lamp, LOW si lamp1, LOW > STOP");
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Subscribe or resubscribe to a topic
// You can subscribe to more topics (to control more LEDs in this example)
client.subscribe("room/lamp");
client.subscribe("room/lamp1");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(lamp, OUTPUT);
pinMode(lamp1, OUTPUT);
pinMode(LED,OUTPUT);
dht.begin();
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
// For this project, you don't need to change anything in the loop function. Basically it ensures that you ESP is connected to your broker
void loop() {
if (!client.connected()) {
reconnect();
}
if(!client.loop())
client.connect("ESP8266Client");
now = millis();
// Publishes new temperature and humidity every 30 seconds
if (now - lastMeasure > 5000) {
lastMeasure = now;
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
// float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
//if (isnan(h) || isnan(t) || isnan(f))
if (isnan(h) || isnan(t)){
Serial.println("Failed to read from DHT sensor!");
return;
}
// Computes temperature values in Celsius
float hic = dht.computeHeatIndex(t, h, false);
static char temperatureTemp[7];
dtostrf(t, 6, 2, temperatureTemp);
static char test[7];
dtostrf(hic, 6, 2, test);
static char humidityTemp[7];
dtostrf(h, 6, 2, humidityTemp);
client.publish("room/temperature", temperatureTemp);
client.publish("room/humidity", humidityTemp);
client.publish("room/test", test);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t Temperature: ");
Serial.print(t);
Serial.print(" *C ");
//Serial.print(f);
Serial.print(" *F\t Heat index: ");
Serial.print(hic);
Serial.println(" *C ");
delay(500);
digitalWrite(LED,HIGH);
delay(500);
digitalWrite(LED,LOW);
}
}
2 реле управляют окном в моей ванной комнате. Если я подключаю ESP32 к источнику питания, все работает, и я могу открыть / закрыть окно, и показания датчика в порядке.
Но после ~ 24 часов я все еще могу видеть показания датчика в реальном времени, но когда я пытаюсь открыть / закрыть в окне ничего не происходит. На MQTT-брокере я вижу сообщения mqtt, но ничего не происходит.
room/lamp1 1
room/lamp1 1
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/temperature 24.00
room/humidity 29.10
room/test 23.22
room/lamp 0
room/lamp 0
room/lamp 2
room/lamp1 2
room/lamp 2
room/lamp1 2
room/lamp 2
room/lamp1 2
room/lamp 2
Любые предложения.