void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// 每5秒向 MQTT 发送一次所有开关的状态数据
if (switchStatusChrono.hasPassed(5000)) {
switchStatusChrono.restart();
sendSwitchStatus();
}
}
### DHT11温湿度传感器 + 控制4路开关 ESP8266源程序(根据设备自选)
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <SimpleDHT.h>
#include <Chrono.h>
const char* deviceID = “esp1”; // ESP8266板子编号,不同的板子更换编号,即可增加板子测点
const char* ssid = “lazykee”;
const char* password = “123456789”;
const char* mqtt_server = “192.168.2.2”;
const int DHT_PIN = 14;
const int SWITCH_PINS[] = { 16, 5, 4, 2 };
const int SWITCH_COUNT = sizeof(SWITCH_PINS) / sizeof(SWITCH_PINS[0]);
WiFiClient espClient;
PubSubClient client(espClient);
SimpleDHT11 dht11(DHT_PIN);
Chrono dht11Chrono;
Chrono switchStatusChrono;
// 更改开关状态并通过 MQTT 发送状态更新
void changeSwitch(int pin, char receivedChar) {
digitalWrite(pin, receivedChar == ‘0’ ? HIGH : LOW);
int pinIndex = -1;
for (int i = 0; i < SWITCH_COUNT; ++i) {
if (SWITCH_PINS[i] == pin) {
pinIndex = i;
break;
}
}
String data = “switch_” + String(pinIndex + 1) + “,” + receivedChar + “;”;
client.publish((String(“zkup/”) + deviceID).c_str(), data.c_str());
}
// MQTT 消息回调函数
void callback(char* topic, byte* payload, unsigned int length) {
char receivedChar = (char)payload[0];
String tp = topic;
Serial.println(tp);
for (int i = 0; i < SWITCH_COUNT; ++i) {
if (tp == (String(“zkDown/”) + deviceID + “/switch_” + String(i + 1))) {
changeSwitch(SWITCH_PINS[i], receivedChar);
break;
}
}
}
// 用于重新连接到 MQTT 服务器的函数
void reconnect() {
while (!client.connected()) {
// 使用 deviceID 作为客户端ID
if (client.connect(deviceID)) {
String subscriptionTopic = String(“zkDown/”) + deviceID + “/#”;
client.subscribe(subscriptionTopic.c_str());
} else {
Serial.print(“failed, rc=”);
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
// 发送 DHT11 传感器数据到 MQTT
void sendDHT11Data() {
byte temperature = 0;
byte humidity = 0;
if (dht11.read(&temperature, &humidity, nullptr) != SimpleDHTErrSuccess) {
return;
}
String data = “temp1,” + String(temperature)