ZK-VIEW平台对接MQTT,实现继电器远程开关与DHT11温湿度采集与传输,通过ZK-VIEW低代码Web组态平台快速接入,实现大屏可视化

本文介绍了如何通过ZK-VIEW低代码平台对接MQTT,实现在嵌入式系统中用ESP8266控制继电器的远程开关,并结合DHT11传感器进行温湿度数据采集和传输。通过定时发送设备状态到MQTT服务器,实现了大屏的实时可视化展示。
摘要由CSDN通过智能技术生成

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)

  • 13
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值