当前位置:网站首页>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
FangToolbar 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 .
边栏推荐
- DeFi借贷协议机制对比:Euler、Compound、Aave和Rari Capital
- Inventory in the first half of 2022: summary of major updates and technical points of 20+ mainstream databases
- 零基础也能做Apple大片!这款免费工具帮你渲染、做特效、丝滑展示
- K-line diagram must be read for quick start
- canvas云朵形状动画
- Key to understanding the trend of spot Silver
- 小程序容器与物联网结合的方式
- Exch:Exchange Server 2013 即将终止支持
- Six photos vous montrent pourquoi TCP serre la main trois fois?
- New research of HKUST & MsrA: about image to image conversion, finishing is all you need
猜你喜欢

Servlet operation principle_ API details_ Advanced path of request response construction (servlet_2)

TFTP download kernel, NFS mount file system

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

2022上半年盘点:20+主流数据库重大更新及技术要点汇总

Interview shock 60: what will cause MySQL index invalidation?

MOOG servo valve d661-4577c

China Infrastructure Development Association: electronic contract is recommended

Building a basic buildreoot file system

NFT: 开启加密艺术时代的无限可能

What will be the game changes brought about by the meta universe?
随机推荐
Shortcut keys for the rainbow brackets plug-in
The new version of Shangding cloud | favorites function has been launched to meet personal use needs
Daily question brushing record (IX)
Rexroth hydraulic control check valve z2s10-1-3x/
canvas鼠标控制重力js特效
Hyper-V: enable SR-IOV in virtual network
【剑指Offer】52. 两个链表的第一个公共节点
小程序容器与物联网结合的方式
Canvas cloud shape animation
MSF后渗透总结
4 years of working experience, and you can't tell the five communication modes between multithreads. Can you believe it?
Small Tools(3) 集成Knife4j3.0.3接口文档
Radio and television 5g officially set sail, attracting attention on how to apply the golden band
MIT science and Technology Review released the list of innovators under the age of 35 in 2022, including alphafold authors, etc
New research of HKUST & MsrA: about image to image conversion, finishing is all you need
AnimeSR:可学习的降质算子与新的真实世界动漫VSR数据集
NFT铸造交易平台开发详情
Vue3 reactive database
[C language] explain threads in detail - solve the problem of shared memory caused by concurrent programs by "locking"
Share 5 commonly used feature selection methods, and you must see them when you get started with machine learning!!!