当前位置:网站首页>Ardunio esp32 obtains real-time temperature and humidity in mqtt protocol (DH11)
Ardunio esp32 obtains real-time temperature and humidity in mqtt protocol (DH11)
2022-06-30 18:00:00 【chenxiky】
esp32 stay mqtt The protocol obtains the temperature and humidity in real time ,mqtt It was built by Alibaba cloud itself `
All the libraries mentioned in this article can be found , I won't offer , If you need to comment, add your own email
This article is in Ardunio1.84 Developed in the environment
dh11 The power supply is connected to 3.3v,data Pick up esp32 D2
#include "DHT.h"
#include <PubSubClient.h>
#include <WiFi.h>
#define WIFI_AP "**"//wifi name
#define WIFI_PASSWORD "*******"//wifi password
#define DHTPIN 2 // DH11 Pick up IO 2
#define DHTTYPE DHT11 // DHT 11
char MqttServer[] = "www.chenxiky.com";// Built mqtt Server domain name or ip The address can be
// Initializing the Ethernet client object -- WiFiClient.h
WiFiClient espClient;
// initialization DHT11 sensor
DHT dht(DHTPIN, DHTTYPE);
// initialization MQTT library PubSubClient.h The object of
PubSubClient client(espClient);
int status = WL_IDLE_STATUS;
unsigned long lastSend;
void setup() {
Serial.begin(9600);
Serial.println(" Temperature and humidity data :");
dht.begin();
InitWiFi(); // Connect WiFi
client.setServer( MqttServer, 1883 ); // Connect WiFi after , Connect MQTT The server
lastSend = 0;
}
void loop() {
status = WiFi.status();
if ( status != WL_CONNECTED) {
while ( status != WL_CONNECTED) {
Serial.print("[loop()]Attempting to connect to WPA SSID: ");
Serial.println(WIFI_AP);
// Connect WiFi hotspot
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(1000);
}
Serial.println("[loop()]Connected to AP");
}
if ( !client.connected() ) {
reconnect();
}
if ( millis() - lastSend > 1000 ) {
// For timing 1 Send data once per second
getAndSendTemperatureAndHumidityData(); // Get the temperature and humidity data and send it to MQTT Go to the server
lastSend = millis();
}
client.loop();
}
/* * * Read temperature and humidity data , Then send it to MQTT Go to the server * */
void getAndSendTemperatureAndHumidityData()
{
Serial.println("Collecting temperature data.");
// Probably 1s Read once
delay(1000);
float h = dht.readHumidity();
float t = dht.readTemperature();
// Check whether the temperature and humidity failed to be read
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
String temperature = String(t);
String humidity = String(h);
// Just debug messages
Serial.print( "Sending temperature and humidity : [" );
Serial.print( temperature ); Serial.print( "," );
Serial.print( humidity );
Serial.print( "] -> " );
// Construct a JSON Format payload String
String payload = "{";
payload += "\"temperature\":"; payload += temperature; payload += ",";
payload += "\"humidity\":"; payload += humidity;
payload += "}";
// Send payload
char attributes[100];
payload.toCharArray( attributes, 100 );
// boolean publish(const char* topic, const char* payload);
//wendu This is the topic of publication , You can receive the temperature and humidity by subscribing to this topic
client.publish( "wendu", attributes );
Serial.print("[publish]-->>");
Serial.println( attributes );
}
void InitWiFi()
{
delay(10);
// Try to connect WiFi The Internet
while ( status != WL_CONNECTED) {
Serial.print("[InitWiFi]Attempting to connect to WPA SSID: ");
Serial.println(WIFI_AP);
// Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(1000);
}
Serial.println("[InitWiFi]Connected to AP");
}
/** * * MQTT Client disconnection reconnection function * */
void reconnect() {
// Keep cycling until it is connected MQTT The server
while (!client.connected()) {
Serial.print("[reconnect]Connecting to MQTT Server ...");
// Try to connect connect Is an overloaded function (clientId, username, password)
if ( client.connect("ESP_32", NULL, NULL) ) {
Serial.println( "[DONE]" );
} else {
Serial.print( "[FAILED] [ mqtt connect error code = " );
Serial.print( client.state() );
Serial.println( " : retrying in 5 seconds]" );// Wait 5 seconds before retrying
delay( 5000 );
}
}
}
边栏推荐
- K-line diagram interpretation and practical application skills (see position entry)
- JS from prototype chain to inheritance
- Small Tools(3) 集成Knife4j3.0.3接口文档
- Solution: STM32 failed to parse data using cjson
- Hyper-V: enable SR-IOV in virtual network
- 应届生毕业之后先就业还是先择业?
- [sword finger offer] 53 - I. find the number I in the sorted array
- Six pictures show you why TCP has three handshakes?
- Acwing game 57
- IEEE TBD SCI影响因子提升至4.271,位列Q1区!
猜你喜欢

IEEE TBD SCI影响因子提升至4.271,位列Q1区!

Implementation of graduation project management system based on SSM

DeFi借贷协议机制对比:Euler、Compound、Aave和Rari Capital

New skill: accelerate node through code cache JS startup

Mo Tianlun salon | Tsinghua qiaojialin: Apache iotdb, originated from Tsinghua, is building an open source ecological road

Design and principle of tubes responsive data system

splitting. JS password display hidden JS effect

4年工作经验,多线程间的5种通信方式都说不出来,你敢信?

ABAP-发布Restful服务

分享 5 大常用的特征选择方法,机器学习入门必看!!!
随机推荐
MSF后渗透总结
Key to understanding the trend of spot Silver
Canvas cloud shape animation
Parker variable displacement piston pump pv092r1k1t1nmmc
中基协:推荐使用电子合同
Bridge emqx cloud data to AWS IOT through the public network
TFTP下载kernel,nfs挂载文件系统
New research of HKUST & MsrA: about image to image conversion, finishing is all you need
Development details of NFT casting trading platform
Map集合
canvas云朵形状动画
AnimeSR:可学习的降质算子与新的真实世界动漫VSR数据集
Is there an optimal solution to the energy consumption anxiety in the data center?
【剑指Offer】53 - I. 在排序数组中查找数字 I
Parker Parker sensor p8s-grflx
墨天轮沙龙 | 清华乔嘉林:Apache IoTDB,源于清华,建设开源生态之路
[machine learning] K-means clustering analysis
后渗透之文件系统+上传下载文件
Exploration and practice of "flow batch integration" in JD
小程序容器与物联网结合的方式