当前位置:网站首页>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 );
}
}
}
边栏推荐
- New power of data analysis -- the first open source integrated real-time HTAP database in China was released by stonedb
- Key to understanding the trend of spot Silver
- 广电5G正式启航,黄金频段将如何应用引关注
- [sword finger offer] 52 The first common node of two linked lists
- Shortcut keys for the rainbow brackets plug-in
- Develop those things: how to add text watermarks to videos?
- . Net ORM framework hisql practice - Chapter 1 - integrating hisql
- . Net ORM framework hisql practice - Chapter 1 - integrating hisql
- How can you choose to work in the county after graduation?
- 【剑指Offer】52. 两个链表的第一个公共节点
猜你喜欢

Acwing game 57

Write the simplest small program in C language Hello World

编译生成busybox文件系统

The new version of Shangding cloud | favorites function has been launched to meet personal use needs

Nft: unlimited possibilities to open the era of encryption Art

Exploration and practice of "flow batch integration" in JD

中基协:推荐使用电子合同

Design and principle of tubes responsive data system

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

知名互联网房屋租赁服务公司物联网关键业务迁移上云实践
随机推荐
Six pictures show you why TCP has three handshakes?
每日面试1题-如何防止CDN防护被绕过
[BJDCTF2020]The mystery of ip|[CISCN2019 华东南赛区]Web11|SSTI注入
Parker Parker sensor p8s-grflx
Shortcut keys for the rainbow brackets plug-in
[零基础学IoT Pwn] 环境搭建
Splitting. JS text title slow loading JS effect
应届生毕业之后先就业还是先择业?
Nft: unlimited possibilities to open the era of encryption Art
[C language] explain threads - start two threads
Synchronized summary
. Net ORM framework hisql practice - Chapter 1 - integrating hisql
What will be the game changes brought about by the meta universe?
How to write a technical proposal
China Infrastructure Development Association: electronic contract is recommended
Login box tricks
What did Tongji and Ali study in the CVPR 2022 best student thesis award? This is an interpretation of yizuo
Exch: repair the missing system mailbox
4年工作经验,多线程间的5种通信方式都说不出来,你敢信?
Canvas cloud shape animation