ESP32读取SHT30温湿度数据上传oneNET MQTT服务器,Arduino环境ESP32程序如下:#include
#include "WiFi.h"
#include "PubSubClient.h"
#include "Ticker.h"
#include
const char *ssid = "*******";
const char *password = "********";
const char *mqtt_server = "183.230.40.96";
const int port = 1883;
#define mqtt_devid "ESP32_01"
#define mqtt_pubid "503228"
#define mqtt_password "version=2018-10-31&res=products%2F503228%2Fdevices%2FESP32_01&et=4079681169&method=md5&sign=Vch%2BWzKGFrhAPMCRX6x1IA%3D%3D"
#define Addr_SHT30 0x44
#define SDA_PIN 21
#define SCL_PIN 22
WiFiClient espClient;
PubSubClient client(espClient);
char msgJson[75];
char dataTemplate[] = "{\"id\":123,\"dp\":{\"cTemp\":[{\"v\":%.2f}],\"humidity\":[{\"v\":%.2f}]}}";
Ticker tim1;
void setupWifi()
{
delay(10);
Serial.println("连接WIFI");
WiFi.begin(ssid, password);
while (!WiFi.isConnected())
{
Serial.print(".");
delay(500);
}
Serial.println("OK");
Serial.println("Wifi连接成功");
}
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.println("message rev:");
Serial.println(topic);
for (size_t i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
}
void sendTempAndHumi()
{
if (client.connected())
{
unsigned int data[6];
Wire.beginTransmission(Addr_SHT30);
Wire.write(0x2C);
Wire.write(0x06);
Wire.endTransmission();
delay(500);
Wire.requestFrom(Addr_SHT30, 6);
if (Wire.available() == 6)
{
data[0] = Wire.read();
data[1] = Wire.read();
data[2] = Wire.read();
data[3] = Wire.read();
data[4] = Wire.read();
data[5] = Wire.read();
}
float cTemp = ((((data[0] * 256.0) + data[1]) * 175) / 65535.0) - 45;
float humidity = ((((data[3] * 256.0) + data[4]) * 100) / 65535.0);
snprintf(msgJson, 75, dataTemplate, cTemp, humidity);
Serial.print("public the data:");
Serial.println(msgJson);
client.publish("$sys/503228/ESP32_01/dp/post/json", (uint8_t *)msgJson, strlen(msgJson));
}
}
void clientReconnect()
{
while (!client.connected())
{
Serial.println("reconnect MQTT...");
if (client.connect(mqtt_devid, mqtt_pubid, mqtt_password))
{
Serial.println("connected");
client.subscribe("$sys/503228/ESP32_01/cmd/request/#");
}
else
{
Serial.println("failed");
Serial.println(client.state());
Serial.println("try again in 5 sec");
delay(5000);
}
}
}
void setup()
{
Wire.begin(SDA_PIN, SCL_PIN);
Serial.begin(115200);
delay(3000);
setupWifi();
client.setServer(mqtt_server, port);
client.connect(mqtt_devid, mqtt_pubid, mqtt_password);
if (client.connected())
{
Serial.println("OneNet is connected!");
}
client.setCallback(callback);
client.subscribe("$sys/503228/ESP32_01/cmd/request/#");
tim1.attach(2, sendTempAndHumi);
}
void loop()
{
if (!WiFi.isConnected())
{
setupWifi();
}
if (!client.connected())
{
clientReconnect();
delay(100);
}
client.loop();
}
根据自己的信息修改程序即可,程序主要流程如下图所示:
程序上传到ESP32,打开串口监视器,可以看到WiFi连接成功,oneNET连接成功以及数据可以正常上传。
用手按在SHT30上,可以看到oneNET上温度曲线在不断变化: