当前位置:网站首页>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 );
}
}
}
边栏推荐
- Development details of NFT casting trading platform
- Mo Tianlun salon | Tsinghua qiaojialin: Apache iotdb, originated from Tsinghua, is building an open source ecological road
- [bjdctf2020]the mystery of ip|[ciscn2019 southeast China division]web11|ssti injection
- Vue3 reactive database
- Thinking on large file processing (upload, download)
- Booking UI effect implemented by svg
- 每日面试1题-如何防止CDN防护被绕过
- [BJDCTF2020]The mystery of ip|[CISCN2019 华东南赛区]Web11|SSTI注入
- 5g business is officially commercial. What are the opportunities for radio and television?
- A tough battle for Tencent cloud
猜你喜欢

Hyper-V: enable SR-IOV in virtual network

Exploration and practice of "flow batch integration" in JD

Vue3 reactive database

Canvas cloud shape animation

Share 5 commonly used feature selection methods, and you must see them when you get started with machine learning!!!

【架构】1366- 如何画出一张优秀的架构图

splitting. JS password display hidden JS effect

Babbitt | yuanuniverse daily must read: minors ask for a refund after a reward. The virtual anchor says he is a big wrongdoer. How do you think of this regulatory loophole

Cloud practice of key business migration of Internet of things by well-known Internet housing rental service companies

MIT科技评论2022年35岁以下创新者名单发布,含AlphaFold作者等
随机推荐
构建基本buildroot文件系统
Map collection
Vue3 reactive database
Rexroth hydraulic control check valve z2s10-1-3x/
Post MSF infiltration summary
Design and principle of tubes responsive data system
Share 5 commonly used feature selection methods, and you must see them when you get started with machine learning!!!
How can you choose to work in the county after graduation?
How to write a technical proposal
Development details of NFT casting trading platform
6 张图带你搞懂 TCP 为什么是三次握手?
Cloud practice of key business migration of Internet of things by well-known Internet housing rental service companies
Six photos vous montrent pourquoi TCP serre la main trois fois?
. Net ORM framework hisql practice - Chapter 1 - integrating hisql
[BJDCTF2020]The mystery of ip|[CISCN2019 华东南赛区]Web11|SSTI注入
中基协:推荐使用电子合同
[C language] detailed explanation of threads - multi threads for collaborative operation
2022上半年盘点:20+主流数据库重大更新及技术要点汇总
生成对抗网络,从DCGAN到StyleGAN、pixel2pixel,人脸生成和图像翻译。
阿里云ECS导入本地,解决部署的问题