Learn how to publish temperature and humidity readings from a DHT11 or DHT22 sensor via MQTT with the ESP8266 NodeMCU to any platform that supports MQTT or any MQTT client. As an example, we’ll publish sensor readings to Node-RED Dashboard and the ESP8266 will be programmed using Arduino IDE.
Recommended reading: What is MQTT and How It Works
Project Overview
The following diagram shows a high-level overview of the project we’ll build.
- The ESP8266 requests temperature and humidity readings from the DHT11 or DHT22 sensor;
- Temperature readings are published in the esp/dht/temperature topic;
- Humidity readings are published in the esp/dht/humidity topic;
- Node-RED is subscribed those topics;
- Node-RED receives the sensor readings and displays them on gauges;
- You can receive the readings in any other platform that supports MQTT and handle the readings as you want.
Prerequisites
Before proceeding with this tutorial, make sure you check the following prerequisites.
Arduino IDE
We’ll program the ESP8266 using Arduino IDE, so make sure you have the ESP8266 add-on installed.
MQTT Broker
To use MQTT, you need a broker. We’ll be using Mosquitto broker installed on a Raspberry Pi. Read How to Install Mosquitto Broker on Raspberry Pi.
You can use any other MQTT broker, including a cloud MQTT broker. We’ll show you how to do that in the code later on.
If you’re not familiar with MQTT make sure you read our introductory tutorial: What is MQTT and How It Works.
MQTT Libraries
To use MQTT with the ESP8266 we’ll use the Async MQTT Client Library.
Installing the Async MQTT Client Library
- Click here to download the Async MQTT client library. You should have a .zip folder in your Downloads folder
- Unzip the .zip folder and you should get async-mqtt-client-master folder
- Rename your folder from
async-mqtt-client-masterto async_mqtt_client - Move the async_mqtt_client folder to your Arduino IDE installation libraries folder
- Finally, re-open your Arduino IDE
Alternatively, you can go to Sketch > Include Library > Add . ZIP library and select the library you’ve just downloaded.
Installing the ESPAsync TCP Library
To use MQTT with the ESP8266, you also need the ESPAsync TCP library.
- Click here to download the ESPAsync TCP client library. You should have a .zip folder in your Downloads folder
- Unzip the .zip folder and you should get ESPAsyncTCP-master folder
- Rename your folder from
ESPAsyncTCP-masterto ESPAsyncTCP - Move the ESPAsyncTCP folder to your Arduino IDE installation libraries folder
- Finally, re-open your Arduino IDE
Alternatively, you can go to Sketch > Include Library > Add . ZIP library and select the library you’ve just downloaded.
DHT Sensor Libraries
To read from the DHT sensor, we’ll use the DHT library from Adafruit. To use this library you also need to install the Adafruit Unified Sensor library. Follow the next steps to install those libraries.
1. Open your Arduino IDE and go to Sketch > Include Library > Manage Libraries. The Library Manager should open.
2. Search for “DHT” on the Search box and install the DHT library from Adafruit.
3. After installing the DHT library from Adafruit, type “Adafruit Unified Sensor” in the search box. Scroll all the way down to find the library and install it.
After installing the libraries, restart your Arduino IDE.
Parts Required
For this tutorial you need the following parts:
- ESP8266 (read Best ESP8266 development boards comparison)
- DHT11 or DHT22 – DHT with ESP8266 Guide
- 4.7k Ohm resistor
- Raspberry Pi board (read Best Raspberry Pi Starter Kits)
- MicroSD Card – 16GB Class10
- Raspberry Pi Power Supply (5V 2.5A)
- Jumper wires
- Breadboard
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Schematic Diagram
Wire the DHT11 or DHT22 to the ESP8266 as shown in the following schematic diagram with the data pin connected to GPIO 14.
Note: if you have a DHT sensor in a breakout board, it comes with only three pins and with an internal pull-up resistor on pin 2, so you don’t need to connect the resistor. You just need to wire VCC, data and GND.
In this example, we’re connecting the DHT data pin to GPIO 14. However, you can use any other suitable digital pin.
Learn how to use the ESP8266 GPIOs with our guide: ESP8266 Pinout Reference: Which GPIO pins should you use?
Code
Copy the following code to your Arduino IDE. To make it work for you, you need to insert your network credentials as well as the MQTT broker details.
/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp8266-nodemcu-mqtt-publish-dht11-dht22-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
#include "DHT.h"
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <AsyncMqttClient.h>
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"
// Raspberri Pi Mosquitto MQTT Broker
#define MQTT_HOST IPAddress(192, 168, 1, XXX)
// For a cloud MQTT broker, type the domain name
//#define MQTT_HOST "example.com"
#define MQTT_PORT 1883
// Temperature MQTT Topics
#define MQTT_PUB_TEMP "esp/dht/temperature"
#define MQTT_PUB_HUM "esp/dht/humidity"
// Digital pin connected to the DHT sensor
#define DHTPIN 14
// Uncomment whatever DHT sensor type you're using
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
// Variables to hold sensor readings
float temp;
float hum;
AsyncMqttClient mqttClient;
Ticker mqttReconnectTimer;
WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;
Ticker wifiReconnectTimer;
unsigned long previousMillis = 0; // Stores last time temperature was published
const long interval = 10000; // Interval at which to publish sensor readings
void connectToWifi() {
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
void onWifiConnect(const WiFiEventStationModeGotIP& event) {
Serial.println("Connected to Wi-Fi.");
connectToMqtt();
}
void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
Serial.println("Disconnected from Wi-Fi.");
mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
wifiReconnectTimer.once(2, connectToWifi);
}
void connectToMqtt() {
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void onMqttConnect(bool sessionPresent) {
Serial.println("Connected to MQTT.");
Serial.print("Session present: ");
Serial.println(sessionPresent);
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
Serial.println("Disconnected from MQTT.");
if (WiFi.isConnected()) {
mqttReconnectTimer.once(2, connectToMqtt);
}
}
/*void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(uint16_t packetId) {
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}*/
void onMqttPublish(uint16_t packetId) {
Serial.print("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup() {
Serial.begin(115200);
Serial.println();
dht.begin();
wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
//mqttClient.onSubscribe(onMqttSubscribe);
//mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
// If your broker requires authentication (username and password), set them below
//mqttClient.setCredentials("REPlACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");
connectToWifi();
}
void loop() {
unsigned long currentMillis = millis();
// Every X number of seconds (interval = 10 seconds)
// it publishes a new MQTT message
if (currentMillis - previousMillis >= interval) {
// Save the last time a new reading was published
previousMillis = currentMillis;
// New DHT sensor readings
hum = dht.readHumidity();
// Read temperature as Celsius (the default)
temp = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
//temp = dht.readTemperature(true);
// Publish an MQTT message on topic esp/dht/temperature
uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());
Serial.printf("Publishing on topic %s at QoS 1, packetId: %i ", MQTT_PUB_TEMP, packetIdPub1);
Serial.printf("Message: %.2f \n", temp);
// Publish an MQTT message on topic esp/dht/humidity
uint16_t packetIdPub2 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(hum).c_str());
Serial.printf("Publishing on topic %s at QoS 1, packetId %i: ", MQTT_PUB_HUM, packetIdPub2);
Serial.printf("Message: %.2f \n", hum);
}
}
How the Code Works
The following section imports all the required libraries.
#include "DHT.h"
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <AsyncMqttClient.h>
Include your network credentials on the following lines.
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"
Insert the Raspberry Pi IP address, so that the ESP8266 connects to your broker.
#define MQTT_HOST IPAddress(192, 168, 1, 106)
If you’re using a cloud MQTT broker, insert the broker domain name, for example:
#define MQTT_HOST "example.com"
Define the MQTT port.
#define MQTT_PORT 1883
The temperature and humidity will be published on the following topics:
#define MQTT_PUB_TEMP "esp/dht/temperature"
#define MQTT_PUB_HUM "esp/dht/humidity"
Define the GPIO that the DHT sensor data pin is connected to. In our case, it is connected to GPIO 14.
#define DHTPIN 14
Uncomment the DHT sensor type you’re using. In our example, we’re using the DHT22.
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
Initialize the DHT sensor on the pin and type defined earlier.
DHT dht(DHTPIN, DHTTYPE);
The temp and hum variables will hold the temperature and humidity values from the DHT22 sensor.
float temp;
float hum;
Create an AsyncMqttClient object called mqttClient to handle the MQTT client and timers to reconnect to your MQTT broker and router when it disconnects.
AsyncMqttClient mqttClient;
Ticker mqttReconnectTimer;
WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;
Ticker wifiReconnectTimer;
Then, create some auxiliary timer variables to publish the readings every 10 seconds. You can change the delay time on the interval variable.
unsigned long previousMillis = 0; // Stores last time temperature was published
const long interval = 10000; // Interval at which to publish sensor readings
Note: the DHT11 and DHT22 have a low sampling rate. You can only request DHT11 readings every second, or every two seconds for the DHT22.
MQTT functions: connect to Wi-Fi, connect to MQTT, and Wi-Fi events
We haven’t added any comments to the functions defined in the next code section. Those functions come with the Async Mqtt Client library. The function’s names are pretty self-explanatory.
For example, the connectToWifi() connects your ESP8266 to your router:
void connectToWifi() {
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
The connectToMqtt() connects your ESP8266 to your MQTT broker:
void connectToMqtt() {
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
The onMqttConnect() function runs after starting a session with the broker.
void onMqttConnect(bool sessionPresent) {
Serial.println("Connected to MQTT.");
Serial.print("Session present: ");
Serial.println(sessionPresent);
}
MQTT functions: disconnect and publish
If the ESP8266 loses connection with the MQTT broker, it calls the onMqttDisconnect function that prints that message in the serial monitor.
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
Serial.println("Disconnected from MQTT.");
if (WiFi.isConnected()) {
mqttReconnectTimer.once(2, connectToMqtt);
}
}
When you publish a message to an MQTT topic, the onMqttPublish() function is called. It prints the packet id in the Serial Monitor.
void onMqttPublish(uint16_t packetId) {
Serial.print("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
Basically, all these functions that we’ve just mentioned are callback functions. So, they are executed asynchronously.
setup()
Now, let’s proceed to the setup(). Initialize the DHT sensor.
dht.begin();
The next two lines create handlers that will allow both the MQTT broker and Wi-Fi connection to reconnect, in case the connection is lost.
wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);
Finally, assign all the callback functions. This means that these functions will be executed automatically when needed. For example, when the ESP8266 connects to the broker, it automatically calls the onMqttConnect() function, and so on.
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
//mqttClient.onSubscribe(onMqttSubscribe);
//mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
Broker Authentication
If your broker requires authentication, uncomment the following line and insert your credentials (username and password).
mqttClient.setCredentials("REPlACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");
Finally, connect to Wi-Fi.
connectToWifi();
loop()
In the loop(), you create a timer that will allow you to get new temperature and humidity readings from the DHT sensor and publishing them on the corresponding topic every 10 seconds.
unsigned long currentMillis = millis();
// Every X number of seconds (interval = 10 seconds)
// it publishes a new MQTT message
if (currentMillis - previousMillis >= interval) {
// Save the last time a new reading was published
previousMillis = currentMillis;
// New DHT sensor readings
hum = dht.readHumidity();
// Read temperature as Celsius (the default)
temp = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
//temp = dht.readTemperature(true);
Publishing to topics
To publish the readings on the corresponding MQTT topics, use the next lines:
uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());
uint16_t packetIdPub2 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(hum).c_str());
Basically, use the publish() method on the mqttClient object to publish data on a topic. The publish() method accepts the following arguments, in order:
- MQTT topic (const char*)
- QoS (uint8_t): quality of service – it can be 0, 1 or 2
- retain flag (bool): retain flag
- payload (const char*) – in this case, the payload corresponds to the sensor reading
The QoS (quality of service) is a way to guarantee that the message is delivered. It can be one of the following levels:
- 0: the message will be delivered once or not at all. The message is not acknowledged. There is no possibility of duplicated messages;
- 1: the message will be delivered at least once, but may be delivered more than once;
- 2: the message is always delivered exactly once;
- Learn about MQTT QoS.
Uploading the code
With your Raspberry Pi powered on and running the Mosquitto MQTT broker, upload the code to your ESP8266.
Open the Serial Monitor at a baud rate of 115200 and you’ll see that the ESP8266 starts publishing messages on the topics we’ve defined previously.
Preparing Node-RED Dashboard
The ESP8266 is publishing temperature readings every 10 seconds on the esp/dht/temperature and esp/dht/humidity topics. Now, you can use any dashboard that supports MQTT or any other device that supports MQTT to subscribe to those topics and receive the readings.
As an example, we’ll create a simple flow using Node-RED to subscribe to those topics and display the readings on gauges.
If you don’t have Node-RED installed, follow the next tutorials:
Having Node-RED running on your Raspberry Pi, go to your Raspberry Pi IP address followed by :1880.
http://raspberry-pi-ip-address:1880
The Node-RED interface should open. Drag two MQTT in nodes, and two gauge nodes to the flow.
Click the MQTT node and edit its properties.
The Server field refers to the MQTT broker. In our case, the MQTT broker is the Raspberry Pi, so it is set to localhost:1883. If you’re using a Cloud MQTT broker, you should change that field.
Insert the topic you want to be subscribed to and the QoS. This previous MQTT node is subscribed to the esp/dht/temperature topic.
Click on the other MQTT in node and edit its properties with the same server, but for the other topic: esp/dht/humidity.
Click on the gauge nodes and edit its properties for each reading. The following node is set for the temperature readings. Edit the other chart node for the humidity readings.
Wire your nodes as shown below:
Finally, deploy your flow (press the button on the upper right corner).
Alternatively, you can go to Menu > Import and copy the following to your Clipboard to create your Node-RED flow.
[{"id":"59f95d85.b6f0b4","type":"mqtt in","z":"b01416d3.f69f38","name":"","topic":"esp/dht/temperature","qos":"1","datatype":"auto","broker":"8db3fac0.99dd48","x":910,"y":340,"wires":[["2babfd19.559212"]]},{"id":"2babfd19.559212","type":"ui_gauge","z":"b01416d3.f69f38","name":"","group":"37de8fe8.46846","order":2,"width":0,"height":0,"gtype":"gage","title":"Temperature","label":"ºC","format":"{{value}}","min":0,"max":"40","colors":["#00b500","#f7df09","#ca3838"],"seg1":"","seg2":"","x":1210,"y":340,"wires":[]},{"id":"b9aa2398.37ca3","type":"mqtt in","z":"b01416d3.f69f38","name":"","topic":"esp/dht/humidity","qos":"1","datatype":"auto","broker":"8db3fac0.99dd48","x":900,"y":420,"wires":[["d0f75e86.1c9ae"]]},{"id":"d0f75e86.1c9ae","type":"ui_gauge","z":"b01416d3.f69f38","name":"","group":"37de8fe8.46846","order":2,"width":0,"height":0,"gtype":"gage","title":"Humidity","label":"%","format":"{{value}}","min":"30","max":"100","colors":["#53a4e6","#1d78a9","#4e38c9"],"seg1":"","seg2":"","x":1200,"y":420,"wires":[]},{"id":"8db3fac0.99dd48","type":"mqtt-broker","z":"","name":"","broker":"localhost","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"37de8fe8.46846","type":"ui_group","z":"","name":"BME280","tab":"53b8c8f9.cfbe48","order":1,"disp":true,"width":"6","collapse":false},{"id":"53b8c8f9.cfbe48","type":"ui_tab","z":"","name":"Home","icon":"dashboard","order":2,"disabled":false,"hidden":false}]
Demonstration
Go to your Raspberry Pi IP address followed by :1880/ui.
http://raspberry-pi-ip-address:1880/ui
You should get access to the current DHT temperature and humidity readings on the Dashboard. You can use other dashboard-type nodes to display the readings on different ways.
That’s it! You have your ESP8266 board publishing DHT temperature and humidity readings to Node-RED via MQTT.
Wrapping Up
MQTT is a great communication protocol to exchange small amounts of data between devices. In this tutorial you’ve learned how to publish temperature and humidity readings from a DHT sensor with the ESP8266 to different MQTT topics. Then, you can use any device or home automation platform to subscribe to those topics and receive the readings.
Instead of a DHT, you can use any a different sensor:
- ESP8266 MQTT – Publish DS18B20 Temperature Readings
- ESP8266 MQTT – Publish BME280 Temperature, Humidity and Pressure Readings
We hope you’ve found this tutorial useful. If you want to learn more about the ESP8266, take a look at our resources:
- Home Automation using ESP8266
- MicroPython Programming with ESP32 and ESP8266
- More ESP8266 NodeMCU Projects…
Thanks for reading.
Hello, Thanks for this tutorial. I was able to deploy this on multiple esp8266’s. After a while though, it would start saying in the serial monitor “Publishing on topic home/temperature at QoS 1, packetId: 1 Message: nan
Publishing on topic home/humidity at QoS 1, packetId 2: Message: nan”
I’m referring to the end when it says Message: nan. How would I fix this?
Thanks
-Cayden
Hi.
That’s an error reading the DHT sensor.
You can read this troubleshooting guide and see if it helps: https://randomnerdtutorials.com/solved-dht11-dht22-failed-to-read-from-dht-sensor/
Regards,
Sara
Hello,
Can you help me find the correct code for mqtt cloud broker in arduino ide? I use this mqtt “broker.mqttdashboard.com” without Raspberry Pi. I get “connecting to mqtt then disconnected from mqtt” in the serial monitor. Thanks in advance.
Hi.
If you’re using a cloud MQTT broker, insert the broker domain name, for example:
#define MQTT_HOST “example.com”
If your broker requires authentication, uncomment the following line and insert your credentials (username and password).
mqttClient.setCredentials(“REPlACE_WITH_YOUR_USER”, “REPLACE_WITH_YOUR_PASSWORD”);
It’s everything explained in the tutorial.
Regards,
Sara
Hi again,
Thank you very much for your answer it was really helpfull. I found the mistake and it was the mqtt port that I used. Now i would like to ask if you can help me with something extra. I want to add in the project a generic led with 2 pins and when the humidity is in >50% (as an example) i want this led open and when its in <40 % its closed and all this automatically. And finally to see the result in node-red and maybe a slider so i can close it or open it and manually.
Thanks in advance.
HELLO,
Can you help me?
I am using nodemcu/esp8266 with AM2302. Serial monitor give”
connecting to MQTT
temp 25 C
hum 60%
disconnected MQTT this is endless
Node-red with windows 10 gives
in startmonitor connect to broker MQTT localhost:1883
dashboard gives all (gauges and so on) except values for temp/hum.
Missing link between ??
Just wanted to thank you for this great tutorial. I am new to the ESP8266 board but was nonetheless able to deploy a DHT11 sensor and publish the output to an existing MQTT broker within minutes. Thanks!
That’s great!
Awesome work 🙂
Hi,
i use your code. If i flashed it, all is running fine. My provlem is: The ESPs are visible in Wifi settings of every device without security. With static IP you can join the Wlan of the ESP. How i can change it to invinsible and secure?
Hey, I can’t find the Gauge node on Node-Red. Maybe they removed it? Can you please tell me what other alternative I can use?
Hi.
Make sure you have installed Node-RED dashboard.
Regards,
Sara
Well, you two have out done yourselves on this one. This is the most clear and cleanest write up and description on mqtt and Nodered that I’ve read. Now, I have to buy one of your books to help support you in keeping up the great work. Hmmm, but, which one to buy ??? 🙂
BG
Thank you!
It depends on what you want to focus on.
Here you can find all our eBooks:https://randomnerdtutorials.com/courses/
If you have any questions regarding our products, you can send an email to support: https://randomnerdtutorials.com/support/
Thanks 🙂
Regards,
Sara
This code looks really robust with reconnects etc rather than a simple proof of concept
Can’t wait to get home and test it out!
I was going to do this on my own… Found your page and simply copy paste and all works.
Thanks for the hard work….
Great!
If anyone is interested..
Here are a few lines to convert the temp/humid into a “humidex” factor.
This is what it feels like when humidity is high.
float F = (t* 1.8000)+32; // first convert to fahrenheit
float HI = -42.379 + 2.04901523 * F + 10.14333127 * h - .22475541 * F * h - .00683783 * F * F - .05481717 * h * h + .00122874 * F * F * h + .00085282 * F * h * h - .00000199 * F * F * h * h;
then back to celsius (if you wish)
Serial.println((HI – 32)*5/9); //(32°F − 32) × 5/9 = 0°C
I use this to control my AC…
Hope this helps someone
Thanks 🙂
Great Project! I made 3 sensors. They all seem to work at ambient temperature. I put one in a fridge and one in a freezer. The freezer drops to ~-3200 degrees. I swapped out the 3rd sensor into the freezer and it does the same thing. The DHT22 is rated to go to -40. The nodemcu and resistor are on the outside of the freezer. Just the DHT22 is on the inside. Hoping for ideas.
Thanks!
Hi, and thanks a lot!
This was EXACTLY the information that I needed for my home automation project using 3x ESP8266 and 1x ESP32 boards, each combined with a DHT11 sensor. Now I can easily monitor the temperature in 4 different rooms in my “Home Assistant” installation.
I just added some code lines: added offset values for temperature and humidity in order to “calibrate” the DHT11 sensor values. And I added “last will and testament” mqtt data in order to see whether the module in online (and thus, if the temperature and humidity values are up to date).
Hi,
Do you mind sharing your code that includes the calibration offset function?
This is great add-on to the the code.
Cheers!
I would share but not home for a few months
Hi.
I keep getting disconnected from MQTT in the serial. I dont understand why this is happening since I don’t have user or password set for the broker and its installed locally on my Rasp Pi.
Can you please help?
Cheers
Greg
Hi.
What is exactly the error message that you get?
Regards,
Sara
Indeed a well explained tutorial.
1. How to handle not to hard code the wifi ssid and password in code. In practical situations. WiFi credentials and mqtt details would be different for user to user.
2. How to handle explicit configuration of wifi and mqtt on press of reset button.
Hi thanks for this nice tutorial
I have the following issue. I installed the latest mosquitto (MQTT v3.1.1) and my problem is that the payload from the esp8266 never arrives to the mqtt host. If I send a payload manually from the terminal everything is working and I get the values displayed to my node-red ui as expected.
Is there anything to be changed to the librairies or the code to be “compatible” with this new version of mqtt or are you thinking of some other mistake that I’ve made?
Thanks
Emmanuel
Hi.
Make sure you enable remote access on the Mosquitto broker: https://randomnerdtutorials.com/how-to-install-mosquitto-broker-on-raspberry-pi/#remote-access
Regards,
Sara
Thanks for your answer.
I found that the problem was that the esp connects to a 5Ghz wifi When I switch to the 2.4Ghz network everything works perfect
Great!
Thanks for sharing the solution.
Regards,
Sara
will this work with homeassistant
Hi. Thanks for the tutorials. I have learnt a lot. May I know do you have tried MQTT with SSL certificates? I am trying to figure out how it does with MQTT broker (raspberry pi) to client (esp8266).
Hello, can I install an MQTT broker on my ESP8266 instead of using a Raspberry Pi? I have a simple project involving two load cells. Or should I get a Raspberry Pi for this purpose?
Hi.
You can’t install a broker on the ESP8266.
You can install on your computer, if you don’t want to install on a Raspberry Pi. Or you can also use a cloud mqtt broker.
Regards,
Sara
I have follow your tutorial & works perfect. I have only one issue. I have publish topic with qos = 1, & also subscribe topic with qos = 1.
qos = 1 ensure that single time data will receive on subscriber.
i am transfering one numeric number 100 times, that time subscriber was disconnected with server,now i turn on subscriber & connect it but no last publish message received.
where i am making mistake?
Hi.
Make sure you set your retain messages to true.
Regards,
Sara