当前位置:网站首页>Ardunio esp32 DH11 real time uploading temperature and humidity Alibaba cloud self built mqtt
Ardunio esp32 DH11 real time uploading temperature and humidity Alibaba cloud self built mqtt
2022-06-30 18:00:00 【chenxiky】
This is esp32 The board , The operating environment is ardunio, The server is
Insert a code chip here
#include "DHT.h"
#include <PubSubClient.h>
#include <WiFi.h>
#define WIFI_AP "**"//wifi name
#define WIFI_PASSWORD "*******"//wifi password
#define DHTPIN 2 // what digital pin we're connected to
#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(2000);
}
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 3s Read once
delay(3000);
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);
client.publish( "wendu", attributes );//wendu This is the topic of the publication , you are here
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(500);
}
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("liefyuan", 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 );
}
}
}
Here is the reference
This article is a reference to a landlord and perfect , In case of infringement , Please contact me , Respect for the original 、 Respect the author .
I will not provide the library file , There are many on Baidu .
Export and import
export
If you want to try this editor , You can edit this article at will . When you finish writing an article , On top
Fang
Toolbar found Article export , Generate a .md Documents or.html Document carried out
Keep locally .
Import
If you want to load a `
You wrote it .md file , In the upper toolbar, you can select
` The import function imports the file with the corresponding extension ,
Continue your work .
边栏推荐
- [C language] detailed explanation of threads - multi threads for collaborative operation
- ABAP-发布Restful服务
- [binary tree] preorder traversal to construct binary search tree
- Combination of applet container and Internet of things
- Daily interview 1 question - basic interview question of blue team - emergency response (1) basic idea process of emergency response +windows intrusion screening idea
- TFTP下载kernel,nfs挂载文件系统
- .NET ORM框架HiSql实战-第一章-集成HiSql
- Parker proportional overflow valve rs10r35s4sn1jw
- Exch: repair the missing system mailbox
- 腾讯云的一场硬仗
猜你喜欢
Rexroth hydraulic control check valve z2s10-1-3x/
4 years of working experience, and you can't tell the five communication modes between multithreads. Can you believe it?
Shortcut keys for the rainbow brackets plug-in
[Netease Yunxin] playback demo build: unable to convert parameter 1 from "asyncmodalrunner *" to "std:: nullptr\u T"**
Booking UI effect implemented by svg
What did Tongji and Ali study in the CVPR 2022 best student thesis award? This is an interpretation of yizuo
The new version of Shangding cloud | favorites function has been launched to meet personal use needs
Six pictures show you why TCP has three handshakes?
Six photos vous montrent pourquoi TCP serre la main trois fois?
零基础也能做Apple大片!这款免费工具帮你渲染、做特效、丝滑展示
随机推荐
[sword finger offer] sword finger offer 53 - ii Missing numbers from 0 to n-1
[sword finger offer] 52 The first common node of two linked lists
[sword finger offer] 53 - I. find the number I in the sorted array
6 張圖帶你搞懂 TCP 為什麼是三次握手?
[Architecture] 1366- how to draw an excellent architecture diagram
编译生成busybox文件系统
巴比特 | 元宇宙每日必读:未成年人打赏后要求退款,虚拟主播称自己是大冤种,怎么看待这个监管漏洞?...
Design and principle of tubes responsive data system
Rainbow Brackets 插件的快捷键
Shutter music recording playing audioplayers
【架构】1366- 如何画出一张优秀的架构图
Flutter custom component
[C language] detailed explanation of threads - multi threads for collaborative operation
阿里云ECS导入本地,解决部署的问题
Write the simplest small program in C language Hello World
Key to understanding the trend of spot Silver
Bridge emqx cloud data to AWS IOT through the public network
Post MSF infiltration summary
Building a basic buildreoot file system
How to write a technical proposal