esp32的MQTT物联网开发记录
Posted Yaadon
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了esp32的MQTT物联网开发记录相关的知识,希望对你有一定的参考价值。
环境依赖
本项目在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 "WiFiClientSecure.h"
#include "PubSubClient.h"
#include "ArduinoJson.h"
GPIO///
#define DHTPIN 15
#define ADCPIN 32
#define DHTTYPE DHT11 // DHT 11
#define LIGHTPIN 2
#define FANPIN 13
GPIO///
配置WiFi
WIFI///
#define WIFI_SSID "TJ***" //wifi名
#define WIFI_PASSWD "tjark***" //wifi密码
WIFI///
配置MQTT
这里的用户名密码参考tuyaMQTT开放协议
MQTT///
#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"
MQTT///
实例化
WiFiClient espClient; //创建网络连接客户端
PubSubClient client(espClient); //创建mqtt客户端
DHT dht(DHTPIN, DHTTYPE); //DHT实例化
连接WiFi
//连接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
//连接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回调函数
// 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()
// put your setup code here, to run once:
pinMode(LIGHTPIN,OUTPUT);
Serial.begin(115200);
setupWifi();
setupMQTT();
dht.begin();
主函数
void loop()
// put your main code here, to run repeatedly:
// Wait a few seconds between measurements.
delay(5000);
// Read humidity data
int h = dht.readHumidity();
// Read temperature as Celsius (the default)
int t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t))
Serial.println(F("Failed to read from DHT sensor!"));
return;
// Read illumination data
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("% "));
// 封装json
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);
// Serial.println(str);
// Sending to MQTT
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后,可在在线调试功能界面调试,查看传感器数据,验证功能
以上是关于esp32的MQTT物联网开发记录的主要内容,如果未能解决你的问题,请参考以下文章
STM32+ESP8266+MQTT协议连接腾讯物联网开发平台
基于ESP32搭建物联网服务器十二(使用MQTT协议与ESP32互动)
13-STM32物联网开发WIFI(ESP8266)+GPRS(Air202)系统方案微信小程序篇(网页版MQTT)