环境依赖
本项目在Windows环境下开发,所使用的软件和三方库如下
- Arduino IDE 1.8.16 (下载地址)
- DHT-sensor-library(地址 移动至 Arduino/libraries) DHT传感器驱动
- Adafruit_Sensor(地址 移动至 Arduino/libraries) DHT传感器依赖
- PubSubClient(工具=>管理库 下载) MQTT库
- ArduinoJson(工具=>管理库 下载) JSON转换工具
注册产品
本项目使用的是涂鸦智能平台提供的MQTT服务
创建产品 选择产品类型,这里以温湿度传感器为例 选择设备接入 完善产品信息 填写功能定义 设备开发界面免费领取2个授权凭证 保存好DeviceID和DeviceSecret,编写程序时填写
编写程序
引脚定义
#include "DHT.h"
#include "WiFi.h"
#include "PubSubClient.h"
#include "ArduinoJson.h"
#define DHTPIN 15
#define ADCPIN 32
#define DHTTYPE DHT11
#define LIGHTPIN 2
#define FANPIN 13
配置WiFi
#define WIFI_SSID "TJ***"
#define WIFI_PASSWD "tjark***"
配置MQTT
这里的用户名密码参考tuyaMQTT开放协议
#define mqttServer "m1.tuyacn.com"
#define mqttPort 1883
#define ClientId "tuyalink_6c7e8f5a8fd2eee79ea***"
#define User "6c7e8f5a8fd2eee79ea***|signMethod=hmacSha256,timestamp=1639372190,securemode=1,accessType=1"
#define Pass "1ccfff232bafe35be78d0eed7e952f7c37cde39b148c8c2f672fedd85875c***"
#define TOPIC "tylink/6c7e8f5a8fd2eee79ea***/thing/property/set"
实例化
WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHTPIN, DHTTYPE);
连接WiFi
void setupWifi()
{
delay(10);
Serial.println("Connecting WIFI");
WiFi.begin(WIFI_SSID, WIFI_PASSWD);
while (!WiFi.isConnected())
{
Serial.print(".");
delay(500);
}
Serial.println("OK");
Serial.println("Wifi connected successfully!");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
连接MQTT
void setupMQTT()
{
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected())
{
Serial.println("Connecting MQTT");
if(client.connect(ClientId,User,Pass))
{
Serial.println("MQTT connected successfully!");
client.subscribe(TOPIC);
}
else
{
Serial.print("Failed with state ");
Serial.println(client.state());
delay(2000);
}
}
}
编写MQTT回调函数
void callback(char * topic,byte * payload,unsigned int length){
DynamicJsonDocument doc(512);
char charbuffer[512];
Serial.print("Message arrived [");
Serial.print(topic);
Serial.println("]");
int i = 0;
for(;i<length;i++){
charbuffer[i] = (char)payload[i];
}
charbuffer[i] = '\0';
DeserializationError error = deserializeJson(doc,charbuffer);
if(error){
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
bool lightOn = doc["data"]["light_switch"];
bool dehumiOn = doc["data"]["dehumi_switch"];
if (lightOn){
digitalWrite(LIGHTPIN,HIGH);
}
else{
digitalWrite(LIGHTPIN,LOW);
}
if (dehumiOn){
digitalWrite(FANPIN,HIGH);
}
else{
digitalWrite(FANPIN,LOW);
}
}
初始化
void setup() {
pinMode(LIGHTPIN,OUTPUT);
Serial.begin(115200);
setupWifi();
setupMQTT();
dht.begin();
}
主函数
void loop() {
delay(5000);
int h = dht.readHumidity();
int t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
float l = analogRead(ADCPIN);
int percent = 100 - l / 4096.0 * 100.0;
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.print(F("C "));
Serial.print(F("illumination: "));
Serial.print(percent);
Serial.println(F("% "));
DynamicJsonDocument doc(512);
DynamicJsonDocument jsdata(256);
DynamicJsonDocument tempdata(32);
DynamicJsonDocument humidata(32);
DynamicJsonDocument illudata(32);
tempdata["value"] = t;
tempdata["time"] = 1639454915;
humidata["value"] = h;
humidata["time"] = 1639454915;
illudata["value"] = percent;
illudata["time"] = 1639454915;
jsdata["temp_current"] = tempdata;
jsdata["humidity_current"] = humidata;
jsdata["illumi_current"] = illudata;
doc["msgId"] = "45lkj3551234001";
doc["time"] = 1639454915;
doc["data"] = jsdata;
String str;
serializeJson(doc, str);
char *p = (char *)str.c_str();
if(client.publish("tylink/6c7e8f5a8fd2eee79ea***/thing/property/report",p) == true)
{
Serial.println("Success sending message.");
}
else
{
Serial.println("Failed sending message.");
}
client.loop();
}
调试验证
程序烧写进esp32后,可在在线调试功能界面调试,查看传感器数据,验证功能
|