当前位置:网站首页>Arduino ide + esp8266+mqtt subscribe to publish temperature and humidity information
Arduino ide + esp8266+mqtt subscribe to publish temperature and humidity information
2022-06-25 19:54:00 【JINYUBAOO】
1、 Library file installation
(1) Install first ESP8266 Support
file -> Preferences -> Add development board manager address
add to http://arduino.esp8266.com/stable/package_esp8266com_index.json
(2) Click Tools - Development board - Development board Manager , Enter the development board manager interface : find esp8266 And install ;
(3) Tools -> Development board -. The selection is as follows 
(4) Download the external library package
Address : https://github.com/JINYU-ZHOU/MQTT-DHT11.git( If you have any other questions, please leave a message )
Point item -> Load the library -> add to .zip library -> Select the compressed package you downloaded , The following window will prompt you whether to install the results !
2、ESP8266 Distribution network
I have read many tutorials of distribution network , I think PubSubClient Library instances are particularly compatible ,. This library can be found in Arduino IDE Found in the library manager of . Tools -> Management of the library -> find PubSubClient Download according to the version you want , Then open the instance 
You just need to add the name and password of the network you want to connect to, and you want to connect to MQTT The address of the server
const char* ssid = "........";// Yours WIFI name
const char* password = "........";// Yours WIFI password
const char* mqtt_server = "broker.mqtt-dashboard.com";
// You want to connect MQTT Server address, such as const char* mqtt_server = "123.57.133.11";
After connecting to the network successfully, the serial port will prompt 
*
If you don't use it indirectly Arduino, Direct connection ESP8266, Need to download ahead of time CH340 perhaps CP2102 The driver ,
I am using CP2102, If you need to leave a message, I will email you .
3、 Temperature and humidity module test
Prerequisite Download DHT11 Corresponding library package , The same address as above . This is the source code , It is only used to test the temperature and humidity module , Subsequent subscriptions also need to be assembled .
#include "DHT.h"
#define DHTPIN 5
#define DHTTYPE DHT11
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE, 15);
void setup() {
// Start Serial
Serial.begin(115200);
// Init DHT
dht.begin();
}
void loop() {
// Reading temperature and humidity
float h = dht.readHumidity();
float t = dht.readTemperature();
// Display data
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C ");
// Wait a few seconds between measurements.
delay(2000);
}
4、 Subscribe and publish information
In my previous blog post, I mentioned subscription and release code , If you want to learn more, you can click MQTT+ardunio+ESP8266 Development
Part of the code for simply releasing information is as follows , Refer to my previous blog for all the codes .
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 20000) {
// Time delay
lastMsg = now;
++value;
snprintf (msg, 75, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("outTopic", msg);
}
This time we need to snprintf (msg, 75, "hello world #%ld", value); In the middle of the hello world #%ld Replace with our temperature and humidity data
Can you do this directly ?
void loop() {
// Reading temperature and humidity
float h = dht.readHumidity();
float t = dht.readTemperature();
void loop() {
...
snprintf (msg, 75, h, value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("outTopic", msg);
}
// Wait a few seconds between measurements.
delay(2000);
}
If you upload directly in this way, an error will be reported !!! You can learn snprintf This function , The third variable is const char
So there's a good way , Change your temperature and humidity data into a string
String data = "{\"H\":" + String(h) +",\"T\":" + String(t)+"}";
We make use of string Function to convert a string to const char type
strcpy(c,data.c_str());//char c[50];
The total code is attached at the end
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHTPIN 5
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE, 15);
// Update these with values suitable for your network.
const char* ssid = "JINYU";
const char* password = "150";
const char* mqtt_server = "123.57.133.11";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
dht.begin();
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
char c[50];
// Display data
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C ");
// Wait a few seconds between measurements.
delay(2000);
String data =String(h) +"," + String(t) ;
strcpy(c,data.c_str());
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, 75, c, value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("outTopic", msg);
}
}
5、 Experimental results


Welcome criticism , I'm also a beginner , Record every simple progress .
I would like to thank the seniors and classmates who helped me !
I hope to become a little attendant of the big guy as soon as possible ~
边栏推荐
- Uni app through uni Navigateto failed to pass parameter (pass object)
- Why are life science enterprises on the cloud in succession?
- Do you want to know how new investors open accounts? Is online account opening safe?
- Error record: preg_ match(): Compilation failed: range out of order in character class at offset 13
- Connecting PHP to MySQL instances in the lamp environment of alicloud's liunx system
- Print 1 cute every 100 milliseconds ~ with a running lantern effect
- Is it safe to open an account with flush?
- Tcp/ip test questions (II)
- Bindgetuserinfo will not pop up
- mysql load data infile
猜你喜欢
![[today in history] June 25: the father of notebook was born; Windows 98 release; First commercial use of generic product code](/img/ef/a26127284fe57ac049a4313d89cf97.png)
[today in history] June 25: the father of notebook was born; Windows 98 release; First commercial use of generic product code
Android Development Notes - Quick Start (from sqllite to room licentiousness) 2

Vulnhub range the planes: mercury

Lilda Bluetooth air conditioning receiver helps create a more comfortable road life

The native JS mobile phone sends SMS cases. After clicking the button, the mobile phone number verification code is sent. The button needs to be disabled and re enabled after 60 seconds

Principles of MySQL clustered index and non clustered index

Vulnhub range - the planes:venus

Bindgetuserinfo will not pop up

On location and scale in CNN

JS asynchronism (I. asynchronous concept, basic use of web worker)
随机推荐
在打新債開戶證券安全嗎?低傭金靠譜嗎
Print 1 cute every 100 milliseconds ~ with a running lantern effect
三、HikariCP获取连接流程源码分析三
wooyun-2014-065513
R language plot visualization: plot visualization of two-dimensional histogram contour (basic 2D histogram contour)
New features of php7
JS asynchronism (I. asynchronous concept, basic use of web worker)
Google cloud SSH enable root password login
ECS 7-day practical training camp (Advanced route) -- day04 -- build a portal using ECs and polardb
What should I pay attention to in GoogleSEO content station optimization?
Huawei released two promotion plans to promote AI talent development and scientific research innovation
3、 Hikaricp source code analysis of connection acquisition process III
Vulnhub range - darkhole 1
Is it safe for tongdaxin to open an account?
Force wechat page font size to be 100%
Hdoj topic 2005 day
Guangzhou Sinovel interactive creates VR Exhibition Hall panoramic online virtual exhibition hall
Panda weekly -2022/02/18
Error record: preg_ match(): Compilation failed: range out of order in character class at offset 13
Use of serialize() and serializearray() methods for form data serialization