Hackster is hosting Hackster Holidays, Ep. 4: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Wednesday!Stream Hackster Holidays, Ep. 4 on Wednesday!
Cmtelesann
Published

MQTT Communication Between NodeMCU and Raspberry Pi 3 B+

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

IntermediateFull instructions provided3 hours8,089
MQTT Communication Between NodeMCU and Raspberry Pi 3 B+

Things used in this project

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.
#V1.0 - No blynk connectivity as they decided to create a new product with no backwards compatibility.
import time
import paho.mqtt.client as mqtt

# Don't forget to change the variables for the MQTT broker!
mqtt_broker_ip = "Broker_IP_Address"
client=mqtt.Client()
    
#Setup callback functions that are called when MQTT events happen linke 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("/#")

#The callback for when a PUBLISH message is recieved 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  
    #room1
    if msg.topic == "/room1/status":
        if msg.payload == "1":
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    if msg.topic == "/room1/status":
        if msg.payload == "0":
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    #room2
    if msg.topic == "/room2/status":
        if msg.payload == "1":
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    if msg.topic == "/room2/status":
        if msg.payload == "0":
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    #room3
    if msg.topic == "/room3/status":
        if msg.payload == "1":
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    if msg.topic == "/room3/status":
        if msg.payload == "0":
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    #room4
    if msg.topic == "/room4/status":
        if msg.payload == "1":
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    if msg.topic == "/room4/status":
        if msg.payload == "0":
            print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))

    #Print humidity and temperature values
    if msg.topic == "/room1/temperature":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    if msg.topic == "/room1/humidity":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    if msg.topic == "/room2/temperature":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    if msg.topic == "/room2/humidity":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    if msg.topic == "/room3/temperature":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    if msg.topic == "/room3/humidity":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    if msg.topic == "/room4/temperature":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
    if msg.topic == "/room4/humidity":
        print ("Topic: ", msg.topic + "\nMessage: " + str(msg.payload))
 
# 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()
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
 - MQTT library
*/

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

const char* mqtt_server = "Broker_IP_Address";             // MQTT Server IP Address
const char* clientID = "Room1";                        // 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 = true;                           
const char* willMessage = "0";                        // 0 - Disconnecetd
int counter = 0;                                      // Used to reconnect to MQTT server
const char* swversion = "1.0";                        // 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 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
  delay(2000);                                        // Delay to allow first connection with MQTT Broker
    
  if (client.connect(clientID,"","", willTopic, willQoS, willRetain, willMessage, true)) {  // Connecting to MQTT Broker
    client.publish(willTopic, "1", true);
    Serial.print(clientID);
    Serial.println(" connected to MQTT Broker!");
  }
  else {
    Serial.print(clientID);
    Serial.println(" connection to MQTT Broker failed...");
  }                                 

  Serial.println("IP address: ");                     // Print IP address
  Serial.println(WiFi.localIP());
}

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, true)) { // clean session, last will message will be kept
     client.publish(willTopic, "1", true);            // Publishing willmessage, retained, so when it disconnects publishers will get the message even if the publisher itself has disconnected
     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

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

Comments