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.
To learn more about the DHT11 or DHT22 temperature sensor, read our guide: ESP32 with DHT11/DHT22 Temperature and Humidity Sensor using Arduino IDE
Parts Required For this tutorial you need the following parts:
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 ESP32 as shown in the following schematic diagram with the data pin connected to GPIO 4 .
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 4 . However, you can use any other suitable digital pin.
Learn how to use the ESP32 GPIOs with our guide: ESP32 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/esp32-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 <WiFi.h>
extern "C" {
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMqttClient.h>
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"
// Raspberry 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 "esp32/dht/temperature"
#define MQTT_PUB_HUM "esp32/dht/humidity"
// Digital pin connected to the DHT sensor
#define DHTPIN 4
// 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;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t 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 connectToMqtt() {
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void WiFiEvent(WiFiEvent_t event) {
Serial.printf("[WiFi-event] event: %d\n", event);
switch(event) {
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
}
}
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()) {
xTimerStart(mqttReconnectTimer, 0);
}
}
/*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();
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
WiFi.onEvent(WiFiEvent);
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);
// Check if any reads failed and exit early (to try again).
if (isnan(temp) || isnan(hum)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Publish an MQTT message on topic esp32/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 esp32/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);
}
} 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.
Preparing Node-RED Dashboard The ESP32 is publishing temperature readings every 10 seconds on the esp32/dht/temperature and esp32/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 esp32/dht/temperature topic.
Click on the other MQTT in node and edit its properties with the same server, but for the other topic: esp32/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" : "5a45b8da.52b0d8" , "type" : "mqtt in" , "z" : "b01416d3.f69f38" , "name" : "" , "topic" : "esp32/dht/temperature" , "qos" : "1" , "datatype" : "auto" , "broker" : "8db3fac0.99dd48" , "x" : 300 , "y" : 60 , "wires" : [ [ "3042e15e.80a4ee" ] ] } , { "id" : "3042e15e.80a4ee" , "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" : 590 , "y" : 60 , "wires" : [ ] } , { "id" : "8ff168f0.0c74a8" , "type" : "mqtt in" , "z" : "b01416d3.f69f38" , "name" : "" , "topic" : "esp32/dht/humidity" , "qos" : "1" , "datatype" : "auto" , "broker" : "8db3fac0.99dd48" , "x" : 290 , "y" : 140 , "wires" : [ [ "29251f29.6687c" ] ] } , { "id" : "29251f29.6687c" , "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" : 580 , "y" : 140 , "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" : "DHT" , "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} ]
View raw code
沒有留言:
張貼留言