更多相关:华为云IOT物联网 论坛
之前带着大家写过使用esp8266接入华为云物联网平台的教程,有小伙伴后台私信,在ESP32接入华为云时遇到了问题,ESP32和ESP8266的代码几乎差不多的,ESP8266代码中用了“ESP8266.h”开发;ESP32可以直接用“WIFI.h”开发,教程基本和esp8266的那期教程一样,有需要的可以直接去看上一篇帖子:教你如何使用esp8266接入华为云物联网平台(IOTDA)(Arduino IDE开发)_MR_J.YW的博客-CSDN博客_怎么接入云平台文章来源:https://www.toymoban.com/news/detail-637451.html
教你如何使用esp8266接入华为云物联网平台(IOTDA)(Arduino IDE开发)-云社区-华为云 (huaweicloud.com)文章来源地址https://www.toymoban.com/news/detail-637451.html
//ESP32接入华为云物联网平台完成属性定时上报
#include <WiFi.h>
#include <PubSubClient.h> //建议使用PubSubClient2.7.0,最新的库不太好用
WiFiClient espClient;
PubSubClient client(espClient);
const char* ssid = "xxxxxx"; //wifi名称
const char* password = "xxxxxx"; //wifi密码
const char* mqttServer = "xxx"; //例如iot-mqtts.cn-north-4.myhuaweicloud.com,详情参考华为云控制台
const int mqttPort = 1883; //例如1883(华为MQTT地址1883,MQTTS地址8883,详情参考华为云控制台)
//三元组:三元组生成链接:https://iot-tool.obs-website.cn-north-4.myhuaweicloud.com/
const char* ClientId ="xxxxxx";
const char* mqttUser ="xxxxxx";
const char* mqttPassword = "xxxxxx";
//注册设备的ID和密钥
#define device_id "xxxxxx"
#define secret "xxxxxx"
//注意修改自己的服务ID
#define Iot_link_Body_Format "{\"services\":[{\"service_id\":\"Dev_data\",\"properties\":{%s"
//参考上报格式:{"services":[{"service_id":"Dev_data","properties":{"temp": 39}}]}
//设备属性上报
#define Iot_link_MQTT_Topic_Report "$oc/devices/"device_id"/sys/properties/report"
int data_temp=1; //模拟上报的温度值
long lastMsg = 0;
void setup() {
//wifi初始化
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
//MQTT初始化
MQTT_Init();
//更多资料欢迎关注微信公众号“IOT趣制作”
}
void loop() {
if (!client.connected()){
MQTT_Init();
}
else client.loop();
long now = millis();
if (now - lastMsg > 5000)//定时上报
{
lastMsg = now;
MQTT_POST();
data_temp++;
}
}
void MQTT_Init()
{
client.setServer(mqttServer, mqttPort);
while (!client.connected())
{
Serial.println("Connecting to MQTT...");
if (client.connect(ClientId, mqttUser, mqttPassword ))
{
Serial.println("connected");
}
else
{
Serial.print("failed with state ");
Serial.print(client.state());
delay(3000);
}
}
}
void MQTT_POST()
{
char properties[32];
char jsonBuf[128];
sprintf(properties,"\"temp\":%d}}]}",data_temp);
sprintf(jsonBuf,Iot_link_Body_Format,properties);
client.publish(Iot_link_MQTT_Topic_Report, jsonBuf);
Serial.println(Iot_link_MQTT_Topic_Report);
Serial.println(jsonBuf);
Serial.println("MQTT Publish OK!");
}
到了这里,关于【代码分享】ESP32接入华为云物联网平台完成属性定时上报(Arduino IDE开发)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!