Introduction
In the world of Internet of Things (IoT), NodeMCU has gained significant popularity as a versatile development board. With its built-in Wi-Fi capabilities and support for the MQTT protocol, NodeMCU allows for seamless communication with other devices and platforms. In this blog post, we will explore how to control external LEDs and display temperature and humidity values from a DHT11 sensor on MQTT using NodeMCU.
Prerequisites
Before we get started, make sure you have the following components and software installed:
- NodeMCU development board
- DHT11 temperature and humidity sensor
- Arduino IDE (Integrated Development Environment)
- MQTT broker (e.g., Mosquitto)
Step 1: Wiring the Components(DHT11,LEDs, NodeMCU)
Connect the DHT11 sensor to the NodeMCU board as follows:
- VCC to 3.3V pin
- GND to GND pin
- Data pin to any available GPIO pin (e.g., D2)
Step 2: Setting Up the Arduino IDE
- Install the Arduino IDE if you haven’t already.
- Open the Arduino IDE and go to File -> Preferences. In the “Additional Boards Manager URLs” field, add the following URL: http://arduino.esp8266.com/stable/package_esp8266com_index.json
- Go to Tools -> Board -> Boards Manager. Search for “esp8266” and install the “esp8266” package.
- Select the NodeMCU board from Tools -> Board.
Step 3: Installing Required Libraries
To work with the DHT11 sensor and MQTT, we need to install some libraries:
- Open the Library Manager by going to Sketch -> Include Library -> Manage Libraries.
- Search for “DHT sensor library” by Adafruit and install it.
- Search for “PubSubClient” by Nick O’Leary and install it.
Step 4: Writing the Code
Copy and paste the following code into the Arduino IDE:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN D5 // Digital pin connected to the DHT sensor
// Uncomment the type of sensor in use:
#define DHTTYPE DHT11 // DHT 11
DHT_Unified dht(DHTPIN, DHTTYPE);
uint32_t delayMS;
// Update these with values suitable for your network.
const char* ssid = "........";
const char* password = "......";
const char* mqtt_server = "test.mosquitto.org";
const char* topic = "Tempdata"; //publish topic
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
String msgStr = "";
float temp, hum;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
digitalWrite(2,0);
delay(200);
digitalWrite(2,1);
delay(200);
}
randomSeed(micros());
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] == '0') {
digitalWrite(D6, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else if ((char)payload[0] == '1') {
digitalWrite(D6, HIGH); // Turn the LED off by making the voltage HIGH
}
else if ((char)payload[0] == '2') {
digitalWrite(D7, HIGH); // Turn the LED off by making the voltage HIGH
}
else if ((char)payload[0] == '3') {
digitalWrite(D7, LOW); // Turn the LED off by making the voltage HIGH
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
// client.publish("device/temp", "Temperature value");
// client.publish("device/humidity", "humidity value");
// ... and resubscribe
client.subscribe("device/led");
// client.subscribe("device/led1");
// client.subscribe("device/led2");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
// pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
pinMode(D6, OUTPUT);
pinMode(D7, OUTPUT);
dht.begin();
sensor_t sensor;
dht.temperature().getSensor(&sensor);
dht.humidity().getSensor(&sensor);
delayMS = sensor.min_delay / 1000;
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
// delay(delayMS);
// Get temperature event and print its value.
sensors_event_t event;
dht.temperature().getEvent(&event);
if (isnan(event.temperature)) {
Serial.println(F("Error reading temperature!"));
}
else {
Serial.print(F("Temperature: "));
Serial.print(event.temperature);
Serial.println(F("°C"));
temp = event.temperature;
}
// Get humidity event and print its value.
dht.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
Serial.println(F("Error reading humidity!"));
}
else {
Serial.print(F("Humidity: "));
Serial.print(event.relative_humidity);
Serial.println(F("%"));
hum = event.relative_humidity;
}
msgStr = String(temp) +","+String(hum);
byte arrSize = msgStr.length() + 1;
char msg[arrSize];
Serial.print("PUBLISH DATA:");
Serial.println(msgStr);
msgStr.toCharArray(msg, arrSize);
client.publishS(topic, msg);
msgStr = "";
delay(50);
}
}
Make sure to replace the placeholders in the code with your actual Wi-Fi and MQTT broker details.
Step 5: Uploading the Code
- Connect your NodeMCU board to your computer via USB.
- In the Arduino IDE, select the correct port under Tools -> Port.
- Click on the “Upload” button to upload the code to the NodeMCU board.
Step 6: Testing the Setup
- Open the Serial Monitor in the Arduino IDE.
- Verify that the NodeMCU successfully connects to your Wi-Fi network and MQTT broker.
- Subscribe to the topics “sensor/temperature” and “sensor/humidity” on your MQTT client to receive the temperature and humidity values.
- Publish the message “on” or “off” to the topic “led/control” to control the built-in LED on the NodeMCU board.
Conclusion:
In this tutorial, we have learned how to control external LEDs and display DHT11 temperature and humidity values on MQTT using NodeMCU. By combining the power of NodeMCU, DHT11 sensor, and MQTT communication, you can create various IoT projects, such as environmental monitoring systems and smart home automation.
Remember to ensure proper electrical connections and always exercise caution when working with electronic components. Feel free to explore further and modify the code to suit your specific project requirements. Happy tinkering!
Note: This tutorial assumes basic familiarity with Arduino programming and MQTT. If you’re new to these concepts, it’s recommended to explore introductory resources to gain a better understanding.
Also, check out our other playlist Rasa Chatbot, Internet of things, Docker, Python Programming, MQTT, etc.
Become a member of our social family on youtube here.
Stay tuned and Happy Learning. ✌🏻😃