当前位置:网站首页>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 );
}
}
}
边栏推荐
- Nft: unlimited possibilities to open the era of encryption Art
- Exch:exchange server 2013 is about to end support
- [zero basic IOT pwn] environment construction
- Flutter custom component
- 编写C语言的最简单小程序Hello world
- Add code block in word (Reprint)
- 【剑指Offer】剑指 Offer 53 - II. 0~n-1中缺失的数字
- What did Tongji and Ali study in the CVPR 2022 best student thesis award? This is an interpretation of yizuo
- 墨天轮沙龙 | 清华乔嘉林:Apache IoTDB,源于清华,建设开源生态之路
- 4 years of working experience, and you can't tell the five communication modes between multithreads. Can you believe it?
猜你喜欢

水平视觉错误效果js特效代码

3D chart effectively improves the level of large data screen

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

Plane intersection and plane equation

MySQL之零碎知识点

如何写一个技术方案

Word中添加代码块(转载)
![[零基础学IoT Pwn] 环境搭建](/img/3b/a0689a1570fcc40bb9a5a4e9cdc63c.png)
[零基础学IoT Pwn] 环境搭建
![[C language] explain threads - thread separation function pthread_ detach](/img/d7/cce6c8afda85376eb569b1a5239c48.png)
[C language] explain threads - thread separation function pthread_ detach

Implementation of graduation project management system based on SSM
随机推荐
leetcode:787. The cheapest transfer flight in station K [k-step shortest path + DFS memory + defaultdict (dict)]
知名互联网房屋租赁服务公司物联网关键业务迁移上云实践
Network: principle and practice of server network card group technology
How can you choose to work in the county after graduation?
How to write a technical proposal
[bjdctf2020]the mystery of ip|[ciscn2019 southeast China division]web11|ssti injection
分享 5 大常用的特征选择方法,机器学习入门必看!!!
Hyper-v:在虚拟网络中启用 SR-IOV
[零基础学IoT Pwn] 环境搭建
leetcode:1042. Do not plant flowers adjacent to each other [randomly fill in qualified + no contradiction will be formed behind + set.pop]
vue3 响应式数据库—— reactive
Advanced Mathematics (Seventh Edition) Tongji University General exercises one person solution
NFT铸造交易平台开发详情
MySQL之零碎知识点
Nft: unlimited possibilities to open the era of encryption Art
canvas鼠标控制重力js特效
What did Tongji and Ali study in the CVPR 2022 best student thesis award? This is an interpretation of yizuo
Distributed machine learning: model average Ma and elastic average easgd (pyspark)
网络:服务器网卡组技术原理与实践
分布式机器学习:模型平均MA与弹性平均EASGD(PySpark)