MicroPython – Getting Started with MQTT on ESP32/ESP8266
Learn how to use MQTT to exchange data between two ESP32/ESP8266 boards using MicroPython firmware - includes code explanation. We'll use Mosquitto MQTT broker.
- Suitable forB.Tech/Diploma IoT/ESP32 students
- Build time1-2 weeks
- LevelBeginner
- Available atAjvika Labs, Kakinada
About this project
In this tutorial, we’ll show you how to use MQTT to exchange data between two ESP32/ESP8266 boards using MicroPython firmware. As an example, we’ll exchange simple text messages between two ESP boards. The idea is to use the concepts learned here to exchange sensor readings, or commands.
Note
:
this tutorial
is compatible with both the ESP32 and ESP8266
development boards.
Prerequisites
Before continuing with this tutorial, make sure you complete the following prerequisites:
MicroPython firmware
To program the ESP32 and ESP8266 with MicroPython, we use uPyCraft IDE as a programming environment. Follow the next tutorials to install uPyCraft IDE and flash MicroPython firmware on your board:
Install uPyCraft IDE:
Windows PC
MacOS X
, or
Linux Ubuntu
Flash/Upload MicroPython Firmware to ESP32 and ESP8266
MQTT Broker
To use MQTT, you need a broker. We’ll be using
Mosquitto broker
installed on a Raspberry Pi. Read
How to Install Mosquitto Broker on Raspberry Pi
If you’re not familiar with MQTT make sure you read our introductory tutorial:
What is MQTT and How It Works
Parts Required
For this tutorial you need two ESP32 or two ESP8266 boards:
2x
ESP32 DEVKIT DOIT board
– read
ESP32 Development Boards Review and Comparison
(alternative) 2x
ESP8266-12E NodeMCU Kit
– read
Best ESP8266 Wi-Fi Development Board
You also need a Raspberry Pi and the following accessories:
Raspberry Pi board
– read
Best Raspberry Pi Starter Kits
MicroSD Card – 32GB Class10
Raspberry Pi Power Supply (5V 2.5A)
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!
Project Overview
Here’s a high-level overview of the project we’ll build:
ESP#1 publishes messages on the
hello
topic. It publishes a “Hello” message followed by a counter (Hello 1, Hello 2, Hello 3, …). It publishes a new message every 5 seconds.
ESP#1 is subscribed to the
notification
topic to receive notifications from the ESP#2 board.
ESP#2 is subscribed to the
hello
topic. ESP #1 is publishing in this topic. Therefore, ESP#2 receives ESP#1 messages.
When ESP#2 receives the messages, it sends a message saying ‘received’. This message is published on the
notification
topic. ESP#1 is subscribed to that topic, so it receives the message.
Preparing ESP#1
Let’s start by preparing ESP#1:
It is subscribed to the
notification
topic
It publishes on the
hello
topic
Importing umqttsimple library
To use MQTT with the ESP32/ESP8266 and MicroPython, you need to install the
umqttsimple
library.
1.
Create a new file by pressing the
New File
button.
2.
Copy the
umqttsimple
library code into it. You can access the
umqttsimple
library code in the following link:
https://raw.githubusercontent.com/RuiSantosdotme/ESP-MicroPython/master/code/MQTT/umqttsimple.py
3.
Save the file by pressing the
Save
button.
4.
Call this new file “
umqttsimple.py
” and press
ok
5.
Click the
Download and Run
button.
6.
The file should be saved on the
device
folder with the name “
umqttsimple.py
” as highlighted in the figure below.
Now, you can use the library functionalities in your code by importing the library.
boot.py
Open the
boot.py
file and copy the following code to ESP#1.
import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
esp.osdebug(None)
import gc
gc.collect()
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'
mqtt_server = 'REPLACE_WITH_YOUR_MQTT_BROKER_IP'
mqtt_user = 'REPLACE_WITH_YOUR_MQTT_USERNAME'
mqtt_pass = 'REPLACE_WITH_YOUR_MQTT_PASSWORD'
#EXAMPLE IP ADDRESS
#mqtt_server = '192.168.1.144'
client_id = ubinascii.hexlify(machine.unique_id())
topic_sub = b'notification'
topic_pub = b'hello'
last_message = 0
message_interval = 5
counter = 0
station = network. WLAN(network. STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
How the Code Works
You need to import all the following libraries:
import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
Set the debug to None and activate the garbage collector.
esp.osdebug(None)
import gc
gc.collect()
In the following variables, you need to enter your network credentials, your broker IP address, the broker username and corresponding password.
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'
mqtt_server = 'REPLACE_WITH_YOUR_MQTT_BROKER_IP'
mqtt_user = 'REPLACE_WITH_YOUR_MQTT_USERNAME'
mqtt_pass = 'REPLACE_WITH_YOUR_MQTT_PASSWORD'
For example, our broker IP address is: 192.168.1.144.
Note:
read
this tutorial
to see how to get your broker IP address.
To create an MQTT client, we need to get the ESP unique ID. That’s what we do in the following line (it is saved on the
client_id
variable).
client_id = ubinascii.hexlify(machine.unique_id())
Next, write the topic the ESP#1 is subscribed to, and the topic it will be publishing messages:
topic_sub = b'
notification
'
topic_pub = b'
hello
'
Then, create the following variables:
last_message = 0
message_interval = 5
counter = 0
The
last_message
variable will hold the last time a message was sent. The
message_interval
is the time between each message sent. Here, we’re setting it to 5 seconds (this means a new message will be sent every 5 seconds). The
counter
variable is simply a counter to be added to the message.
After that, we make the procedures to connect to the network.
station = network. WLAN(network. STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
main.py
In the
main.py
file is where we’ll write the code to publish and receive the messages. Copy the following code to your
main.py
file.
def sub_cb(topic, msg):
print((topic, msg))
if topic == b'notification' and msg == b'received':
print('ESP received hello message')
def connect_and_subscribe():
global client_id, mqtt_server, topic_sub
client = MQTTClient(client_id, mqtt_server, user=mqtt_user, password=mqtt_pass)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub)
print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
return client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
try:
client = connect_and_subscribe()
except OSError as e:
restart_and_reconnect()
while True:
try:
client.check_msg()
if (time.time() - last_message) > message_interval:
msg = b'Hello #%d' % counter
client.publish(topic_pub, msg)
last_message = time.time()
counter += 1
except OSError as e:
restart_and_reconnect()
How the code works
The first thing you should do is creating a callback function that will run whenever a message is published on a topic the ESP is subscribed to.
Callback function
The callback function should accept as parameters the topic and the message.
def
sub_cb(topic, msg)
:
print((topic, msg))
if topic == b'notification' and msg == b'received':
print('ESP received hello message')
In our callback function, we start by printing the topic and the message. Then, we check if the message was published on the
notification
topic, and if the content of the message is ‘received’. If this if statement is True, it means that ESP#2 received the ‘hello’ message sent by ESP#1.
Basically, this callback function handles what happens when a certain message is received on a certain topic.
Connect and subscribe
Then, we have the
connect_an
Note
:
this tutorial
is compatible with both the ESP32 and ESP8266
development boards.
Prerequisites
Before continuing with this tutorial, make sure you complete the following prerequisites:
MicroPython firmware
To program the ESP32 and ESP8266 with MicroPython, we use uPyCraft IDE as a programming environment. Follow the next tutorials to install uPyCraft IDE and flash MicroPython firmware on your board:
Install uPyCraft IDE:
Windows PC
MacOS X
, or
Linux Ubuntu
Flash/Upload MicroPython Firmware to ESP32 and ESP8266
MQTT Broker
To use MQTT, you need a broker. We’ll be using
Mosquitto broker
installed on a Raspberry Pi. Read
How to Install Mosquitto Broker on Raspberry Pi
If you’re not familiar with MQTT make sure you read our introductory tutorial:
What is MQTT and How It Works
Parts Required
For this tutorial you need two ESP32 or two ESP8266 boards:
2x
ESP32 DEVKIT DOIT board
– read
ESP32 Development Boards Review and Comparison
(alternative) 2x
ESP8266-12E NodeMCU Kit
– read
Best ESP8266 Wi-Fi Development Board
You also need a Raspberry Pi and the following accessories:
Raspberry Pi board
– read
Best Raspberry Pi Starter Kits
MicroSD Card – 32GB Class10
Raspberry Pi Power Supply (5V 2.5A)
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!
Project Overview
Here’s a high-level overview of the project we’ll build:
ESP#1 publishes messages on the
hello
topic. It publishes a “Hello” message followed by a counter (Hello 1, Hello 2, Hello 3, …). It publishes a new message every 5 seconds.
ESP#1 is subscribed to the
notification
topic to receive notifications from the ESP#2 board.
ESP#2 is subscribed to the
hello
topic. ESP #1 is publishing in this topic. Therefore, ESP#2 receives ESP#1 messages.
When ESP#2 receives the messages, it sends a message saying ‘received’. This message is published on the
notification
topic. ESP#1 is subscribed to that topic, so it receives the message.
Preparing ESP#1
Let’s start by preparing ESP#1:
It is subscribed to the
notification
topic
It publishes on the
hello
topic
Importing umqttsimple library
To use MQTT with the ESP32/ESP8266 and MicroPython, you need to install the
umqttsimple
library.
1.
Create a new file by pressing the
New File
button.
2.
Copy the
umqttsimple
library code into it. You can access the
umqttsimple
library code in the following link:
https://raw.githubusercontent.com/RuiSantosdotme/ESP-MicroPython/master/code/MQTT/umqttsimple.py
3.
Save the file by pressing the
Save
button.
4.
Call this new file “
umqttsimple.py
” and press
ok
5.
Click the
Download and Run
button.
6.
The file should be saved on the
device
folder with the name “
umqttsimple.py
” as highlighted in the figure below.
Now, you can use the library functionalities in your code by importing the library.
boot.py
Open the
boot.py
file and copy the following code to ESP#1.
import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
esp.osdebug(None)
import gc
gc.collect()
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'
mqtt_server = 'REPLACE_WITH_YOUR_MQTT_BROKER_IP'
mqtt_user = 'REPLACE_WITH_YOUR_MQTT_USERNAME'
mqtt_pass = 'REPLACE_WITH_YOUR_MQTT_PASSWORD'
#EXAMPLE IP ADDRESS
#mqtt_server = '192.168.1.144'
client_id = ubinascii.hexlify(machine.unique_id())
topic_sub = b'notification'
topic_pub = b'hello'
last_message = 0
message_interval = 5
counter = 0
station = network. WLAN(network. STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
How the Code Works
You need to import all the following libraries:
import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
Set the debug to None and activate the garbage collector.
esp.osdebug(None)
import gc
gc.collect()
In the following variables, you need to enter your network credentials, your broker IP address, the broker username and corresponding password.
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'
mqtt_server = 'REPLACE_WITH_YOUR_MQTT_BROKER_IP'
mqtt_user = 'REPLACE_WITH_YOUR_MQTT_USERNAME'
mqtt_pass = 'REPLACE_WITH_YOUR_MQTT_PASSWORD'
For example, our broker IP address is: 192.168.1.144.
Note:
read
this tutorial
to see how to get your broker IP address.
To create an MQTT client, we need to get the ESP unique ID. That’s what we do in the following line (it is saved on the
client_id
variable).
client_id = ubinascii.hexlify(machine.unique_id())
Next, write the topic the ESP#1 is subscribed to, and the topic it will be publishing messages:
topic_sub = b'
notification
'
topic_pub = b'
hello
'
Then, create the following variables:
last_message = 0
message_interval = 5
counter = 0
The
last_message
variable will hold the last time a message was sent. The
message_interval
is the time between each message sent. Here, we’re setting it to 5 seconds (this means a new message will be sent every 5 seconds). The
counter
variable is simply a counter to be added to the message.
After that, we make the procedures to connect to the network.
station = network. WLAN(network. STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
main.py
In the
main.py
file is where we’ll write the code to publish and receive the messages. Copy the following code to your
main.py
file.
def sub_cb(topic, msg):
print((topic, msg))
if topic == b'notification' and msg == b'received':
print('ESP received hello message')
def connect_and_subscribe():
global client_id, mqtt_server, topic_sub
client = MQTTClient(client_id, mqtt_server, user=mqtt_user, password=mqtt_pass)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub)
print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
return client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
try:
client = connect_and_subscribe()
except OSError as e:
restart_and_reconnect()
while True:
try:
client.check_msg()
if (time.time() - last_message) > message_interval:
msg = b'Hello #%d' % counter
client.publish(topic_pub, msg)
last_message = time.time()
counter += 1
except OSError as e:
restart_and_reconnect()
How the code works
The first thing you should do is creating a callback function that will run whenever a message is published on a topic the ESP is subscribed to.
Callback function
The callback function should accept as parameters the topic and the message.
def
sub_cb(topic, msg)
:
print((topic, msg))
if topic == b'notification' and msg == b'received':
print('ESP received hello message')
In our callback function, we start by printing the topic and the message. Then, we check if the message was published on the
notification
topic, and if the content of the message is ‘received’. If this if statement is True, it means that ESP#2 received the ‘hello’ message sent by ESP#1.
Basically, this callback function handles what happens when a certain message is received on a certain topic.
Connect and subscribe
Then, we have the
connect_an
Technologies used
Hardware components
- ESP32
- ESP8266
- Raspberry Pi
- SD Card
Software & tools
- MQTT
- MicroPython
What you get
- Working project / hardware kit, tested before delivery
- Complete source code with explanation
- Project demo and guidance for your viva
- Project report, PPT and IEEE paper support (on request)
Delivery & Payment
Delivery takes a minimum of two weeks from the date your inquiry is confirmed.
Payment is in two parts:
• 50% advance to start the project
• Remaining 50% before delivery
Note:
• Documentation and PPT are not included by default
• If you need documentation/PPT, it can be arranged for extra time and cost
We'll confirm the exact timeline and cost with you after reviewing your requirements.