IoT ESPWroom32 , Using Node-Red & Raspberry pi 3 through MQTT Protocole
Overview
In this article, we’re going to go over fundamental principle of IoT programmation. This project shows how to use MQTT communication protocol with the ESP32 to publish messages and subscribe to topics. As an example, we’ll publish light state readings to the Node-RED Dashboard, and control an ESP32 output. The ESP32 we’ll be programmed using Arduino IDE and Raspberry pi 3 as broker.
We’ll use the Mosquitto broker installed on the same Raspberry Pi. The broker is responsible for receiving all messages, filtering the messages, decide who is interested in them and publishing the messages to all subscribed clients.
The following figure shows an overview of what we’re going to do in this tutorial.
- The Node-RED application publishes messages (“on” or “off“) in the topic esp32/output. The ESP32 is subscribed to that topic. So, it receives the message with “on” or “off” to turn the LED on or off.
Prerequisites
- You should be familiar with the Raspberry Pi — read Getting Started with Raspberry Pi.
- You should have the Raspbian operating system installed in your Raspberry Pi — watch this youtube video for installing Raspbian Lite, Enabling and Connecting with SSH.
- You need Node-RED installed on your Raspberry Pi and Node-RED Dashboard library afterwards
- Learn what’s MQTT and how it works.
Parts Required
These are the parts required to build the circuit
- Raspberry Pi — read Best Raspberry Pi 3 Starter Kits
- ESPWroom32
- 1x 5mm LED
- 1x 220 Ohm resistor
- Breadboard
- Jumper wires
If you are really passionate about it or else you want to learn IOT, i recommend to buy a starter kit arduino it’s worth it.
Schematic
We’re going to communicate with our raspberrypi were mosquitto broker is installed and Node-Red which running on our browser.We’ll also control an ESP32 output LED connected to GPIO 4.
Here’s how your circuit should look:
Preparing the Arduino IDE
There’s an add-on for the Arduino IDE that allows you to program the ESP32 using the Arduino IDE and its programming language. Follow one of the next tutorials to prepare your Arduino IDE to work with the ESP32, if you haven’t already.
- Windows instructions — ESP32 Board in Arduino IDE
- Mac and Linux instructions — ESP32 Board in Arduino IDE
Installing the ESP32 Add-on on Arduino IDE
A. Installing the ESP32 Board
To install the ESP32 board in your Arduino IDE, follow these next instructions:
1) Open the preferences window from the Arduino IDE. Go to Arduino > Preferences
2) Enter https://dl.espressif.com/dl/package_esp32_index.json into the “Additional Board Manager URLs” field as shown in the figure below. Then, click the “OK” button:
Note: if you already have boards recorded as URL, you can separate the URLs with a comma as follows:
https://dl.espressif.com/dl/package_esp32_index.json, http://arduino.esp8266.com/stable/package_esp8266com_index.json
Open boards manager. Go to Tools > Board > Boards Manager
Search for ESP32 and press install button for the “ESP32 by Espressif Systems“:
B. Installing the PubSubClient Library
The PubSubClient library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT (basically allows your ESP32 to talk with Node-RED).
- Click here to download the PubSubClient library. You should have a .zip folder in your Downloads folder
- Unzip the .zip folder and you should get pubsubclient-master folder
- Rename your folder from pubsubclient-master to pubsubclient
- Move the pubsubclient folder to your Arduino IDE installation libraries folder
- Then, re-open your Arduino IDE
The library comes with a number of example sketches. See File >Examples > PubSubClient within the Arduino IDE software.
C. Process to Upload
Plug the ESP32 board to your computer. Then, follow these steps:
- Open the Arduino IDE
2) Select the Port linked to your controller (NB : you will need a special cable in view to upload the code to the espWroom32).
In my case :
Don’t hesistate to test your code with an exemple sketch before upload the real code.It’s important to work around with the IDE Arduino if you are not familiar with it.
D. Uploading code
Now, you can upload the following code to your ESP32. The code is commented on where you need to make changes. You need to edit the code with your own SSID, password and Raspberry Pi IP address.
/*********
Rodolphe Beloncle
Complete project details at https://github.com/RodolpheBeloncle/IOT-Projects
*********/
#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
// Replace the next variables with your SSID/Password combination
// name of your livebox
const char* ssid = "REPLACE_WITH_YOUR_SSID";
// password to get access to your livebox
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "192.168.1.144";
const char* mqtt_server = "YOUR_MQTT_BROKER_IP_ADDRESS";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
// LED Pin
const int ledPin = 4;
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(ledPin, OUTPUT);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
// Feel free to add more if statements to control more GPIOs with MQTT
// If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
// Changes the output state according to the message
if (String(topic) == "esp32/output") {
Serial.print("Changing output to ");
if(messageTemp == "on"){
Serial.println("on");
digitalWrite(ledPin, HIGH);
}
else if(messageTemp == "off"){
Serial.println("off");
digitalWrite(ledPin, LOW);
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Subscribe
client.subscribe("esp32/output");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 5000) {
lastMsg = now;
}
}
Subscribing to MQTT topics
NB : You don’t need to understand every lines of the code but just understand what it does.Basically after importing different library and set up variables, the controller going to connect to your wifi box and then subscribe to the raspberry pi where the MQTT broker is installed.This controller subscribe to the topic name “esp32/output”, like that it can listen(subscribe) or send messages(publish).
The ESP32 is subscribed to the “esp32/output” topic to receive the messages published on that topic by the Node-RED application. Then, accordingly to the MQTT topic received message, it turns the LED on or off.
Settup Mosquitto Broker on your Raspberry Pi
Installing Mosquitto Broker
Launch your mosquitto broker width the following command in our exemple: sudo mosquitto_sub -d -t esp32/output
Mosquitto Broker test :
Arduino Broker test :
!!! It’s important to test each synchronised devices in view to see if every part of the project are working find.And that the best way to understand what’s append between devices. !!!
Creating the Node-RED flow
Before creating the flow, you need to have installed in your Raspberry Pi:
After that, import the Node-RED flow provided. Go to the GitHub repository.
Next, in the Node-RED window, at the top right corner, select the menu, and go to Import > Clipboard.
Then, paste the code provided and click Import.
After making any changes, click the Deploy button to save all the changes.
Node-RED UI
Now, your Node-RED application is ready. To access Node-RED UI and see how your application looks, access any browser in your local network and type:
http://Your_RPi_IP_address:1880/ui
Your application should look as shown in the following figure. You can control the LED on and off with the switch.
I wanted to keep it simple to be more understandable.
Open the Arduino IDE serial monitor to take a look at the MQTT messages being received and published.
Wrapping Up
In summary, I’ve shown you the basic concepts that allow you to turn on lights and monitor with your ESPWroom32 using Node-RED and the MQTT communication protocol. You can use this example to integrate in your own home automation system and control more outputs.