Cmtelesann
Published

MQTT Communication Between NodeMCU and Raspberry Pi 3 B+

Using MQTT, NodeMCU, DHT22, RaspberryPi and Blynk to monitor temperature and humidity.

IntermediateWork in progress3 hours355
MQTT Communication Between NodeMCU and Raspberry Pi 3 B+

Things used in this project

Hardware components

Raspberry Pi 3 Model B+
Raspberry Pi 3 Model B+
×1
NodeMCU ESP8266 Breakout Board
NodeMCU ESP8266 Breakout Board
×10
DHT22 Temperature and Humidity Sensor
DFRobot DHT22 Temperature and Humidity Sensor
×10
9V 1A Switching Wall Power Supply
9V 1A Switching Wall Power Supply
×2
NodeMcu Base ESP8266 Testing
×10
Graphic OLED, 128 x 32 Pixels
Graphic OLED, 128 x 32 Pixels
×1

Software apps and online services

Blynk
Blynk
Raspbian
Raspberry Pi Raspbian
Thonny Python IDE

Story

Read more

Schematics

NodeMCU + DHT-22

Code

Raspberry Pi

Python
Have this script on your Raspberry Pi. Remember to include your Blynk Auth number, BrokerIPAddress and check the topics subscribed.
import time 
import paho.mqtt.client as mqtt
import blynklib

# Don't forget to change the variables for the MQTT broker!
mqtt_broker_ip = "BROKER_IP"
client = mqtt.Client()

BLYNK_AUTH = 'BLYNK_AUTH'
blynk = blynklib.Blynk(BLYNK_AUTH)

# Setup callback functions that are called when MQTT events happen like 
# connecting to the server or receiving data from a subscribed feed. 
def on_connect(client, userdata, flags, rc): 
    print("Connected with result code " + str(rc)) 
    client.subscribe("/#")
    client.publish("/restart", "1")

# The callback for when a PUBLISH message is received from the server. 
def on_message(client, userdata, msg):
    msg.payload = msg.payload.decode("utf-8") #to decode message, remove b and ''
# Show status of sensors   
    if msg.topic == "/room1/status":
        if msg.payload == "1":
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
            blynk.virtual_write(12,255) #updates Blynl LED status to ON V12
        else:
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
            blynk.virtual_write(12,0)   #updates Blynl LED status to OFF V12         
    if msg.topic == "/room2/status":
        if msg.payload == "1":
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
            blynk.virtual_write(22,255) #updates Blynl LED status to ON V22
        else:
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
            blynk.virtual_write(22,0)   #updates Blynl LED status to OFF V22         
    if msg.topic == "/room3/status":
        if msg.payload == "1":
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
            blynk.virtual_write(32,255) #updates Blynl LED status to ON V32
        else:
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
            blynk.virtual_write(32,0)   #updates Blynl LED status to OFF V32
    # Add as many rooms as you like. Follow a pattern creating virtual pins on blynk (VXX).
            
#Print humidity and temperature values  
    if msg.topic == "/room1/temperature":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
        blynk.virtual_write(10, str(msg.payload)) #to send data to blynk virtual pin V10
    if msg.topic == "/room1/humidity":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
        blynk.virtual_write(11, str(msg.payload)) #to send data to blynk virtual pin V11
    if msg.topic == "/room2/temperature":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
        blynk.virtual_write(20, str(msg.payload)) #to send data to blynk virtual pin V20
    if msg.topic == "/room2/humidity":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
        blynk.virtual_write(21, str(msg.payload)) #to send data to blynk virtual pin V21
    if msg.topic == "/room3/temperature":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
        blynk.virtual_write(30, str(msg.payload)) #to send data to blynk virtual pin V30
    if msg.topic == "/room3/humidity":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
        blynk.virtual_write(31, str(msg.payload)) #to send data to blynk virtual pin V31
    # Add as many rooms as you like. Follow a pattern creating virtual pins on blynk (VXX).
   

# Here, we are telling the client which functions are to be run
# on connecting, and on receiving a message
client.on_connect = on_connect
client.on_message = on_message

# Once everything has been set up, we can (finally) connect to the broker
# 1883 is the listener port that the MQTT broker is using
client.connect(mqtt_broker_ip, 1883)

# Once we have told the client to connect, let the client object run itself
client.loop_forever()
client.disconnect()
blynk.run()
time.sleep(30)

NodeMCU

Arduino
This code should be used on a NodeMCU. Remember to change the device name for debugging purposes. Also put your broker IP Address.
/* REQUIRES the following Arduino libraries:
 - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
 - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
*/

#include <ESP8266WiFi.h>                              // Esp8266 Library
#include <PubSubClient.h>                             // MQTT Library
#include "DHT.h"                                      // DHT Sensor

const char* mqtt_server = "xxx.xxx.xxx.xxx";             // MQTT Server IP Address
const char* clientID = "ClientID"                     // The client id identifies the NodeMCU device.
const char* topicT = "/room1/temperature";          // Topic temperature
const char* topicH = "/room1/humidity";             // Topic humidity
const char* willTopic = "/room1/status";            // Topic Status
int willQoS = 0;
boolean willRetain = false;
const char* willMessage = "0";
int counter = 0;                                      // Used to reconnect to MQTT server
const char* swversion = "0.1";                        // Software version

WiFiClient wifiClient;
PubSubClient client(mqtt_server, 1883, wifiClient);   // 1883 is the listener port for the Broker

DHT dhtA(2, DHT22);                                   // DHT instance named dhtA, Pin on NodeMCU D4 (2) and sensor type

void setup() {
  Serial.begin(9600);                                 // Debug purposes only to check if DHT and connection with MQTT Broker are working
  Serial.print(swversion);                            // Debug. Software version
  dhtA.begin();                                       // Starting the DHT-22

  if (client.connect(clientID, willTopic, willQoS, willRetain, willMessage)) {  // Connecting to MQTT Broker
    client.publish(willTopic, "1");                   // Publish "1" to broker triggering status as "OFF"
    Serial.print(clientID);
    Serial.println(" connected to MQTT Broker!");
  }
  else {
    Serial.print(clientID);
    Serial.println(" connection to MQTT Broker failed...");
  }
  delay(2000);                                        // Delay to allow first connection with MQTT Broker
}

void loop() {
  climateRoutine();                                   // Climate routines 
  if (!client.connected()) {                          // Reconnecting to MQTT server if connection is lost
    reconnect();
  } 
}

void climateRoutine() {
  char temp[16];
  dtostrf(dhtA.readTemperature(), 3, 2, temp);        // To convert float into char
  client.publish(topicT, temp);                        // Publishing temperature 
                 
  char humi[16];
  dtostrf(dhtA.readHumidity(), 3, 2, humi);           // To convert float into char
  client.publish(topicH, humi);                        // Publishing humidity 
    
  if (isnan(temp[16]) || isnan(humi[16])) {           // Check if there DHT is working
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  delay(1000);                                        // Delay to avoid flooding system with data
}

void reconnect() {                                    // Reconnecting to MQTT server if connection is lost
 while (!client.connected()) {
   Serial.print("Attempting MQTT connection...");
   if (client.connect(clientID, willTopic, willQoS, willRetain, willMessage)) {
     client.publish(willTopic, "1");                                     // Publish "1" to broker triggering status as "OFF" 
     Serial.println("Connected to MQTT Broker!");
     counter = 0;
   } else {
     Serial.println("Connection to MQTT Broker failed. Trying again in 2 seconds");
     ++counter;
     if (counter > 180) ESP.reset();
     delay(2000);
   }
 }
}

Credits

Cmtelesann

Cmtelesann

4 projects • 4 followers
Keeping my head busy! Looking for challenges! Trying to keep up with evolution! IoT is the future!

Comments

Add projectSign up / Login