0-ESP32-MicroPython ESP32 ESP8266 MicroPython MQTT Project Tech

MicroPython – Getting Started with MQTT on ESP32/ESP8266

MicroPython Getting Started with MQTT on ESP32/ESP8266

On this tutorial, we’ll present you the best way to use MQTT to trade knowledge between two ESP32/ESP8266 boards utilizing MicroPython firmware. For instance, we’ll trade easy textual content messages between two ESP boards. The thought is to make use of the ideas discovered right here to change sensor readings, or instructions.

Notice: this tutorial is suitable with each the ESP32 and ESP8266 improvement boards. 


Earlier than persevering with with this tutorial, ensure you full the next conditions:

MicroPython firmware

To program the ESP32 and ESP8266 with MicroPython, we use uPyCraft IDE as a programming setting. Comply with the subsequent tutorials to put in uPyCraft IDE and flash MicroPython firmware in your board:

MQTT Dealer

To make use of MQTT, you want a dealer. We’ll be utilizing Mosquitto dealer put in on a Raspberry Pi. Learn Methods to Set up Mosquitto Dealer on Raspberry Pi.

For those who’re not acquainted with MQTT be sure to learn our introductory tutorial: What’s MQTT and How It Works

Elements Required

For this tutorial you want two ESP32 or two ESP8266 boards:

You additionally want a Raspberry Pi and the next equipment:

You need to use the previous hyperlinks or go on to MakerAdvisor.com/instruments to seek out all of the elements in your tasks at one of the best worth!

Venture Overview

Right here’s a high-level overview of the undertaking we’ll construct:

  • ESP#1 publishes messages on the howdy matter. It publishes a “Hiya” message adopted by a counter (Whats up 1, Whats up 2, Whats up three, …). It publishes a brand new message each 5 seconds.
  • ESP#1 is subscribed to the notification matter to obtain notifications from the ESP#2 board.
  • ESP#2 is subscribed to the howdy matter. ESP #1 is publishing on this matter. Subsequently, ESP#2 receives ESP#1 messages.
  • When ESP#2 receives the messages, it sends a message saying ‘acquired’. This message is revealed on the notification matter. ESP#1 is subscribed to that matter, so it receives the message.

Getting ready ESP#1

Let’s begin by getting ready ESP#1:

  • It’s subscribed to the notification matter
  • It publishes on the howdy matter

Importing umqtttsimple library

To make use of MQTT with the ESP32/ESP8266 and MicroPython, you have to set up the umqttsimple library.

1. Create a brand new file by urgent the New File button.

2. Copy the umqttsimple library code into it. You’ll be able to entry the umqttsimple library code within the following hyperlink:

three. Save the file by urgent the Save button.

four. Name this new file “umqttsimple.py” and press okay.

5. Click on the Obtain and Run button.

6. The file must be saved on the gadget folder with the identify “umqttsimple.py” as highlighted within the determine under.

Now, you need to use the library functionalities in your code by importing the library.


Open the boot.py file and replica the next code to ESP#1.

How the Code Works

You want to import all the next libraries:

import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import community
import esp

Set the debug to None and activate the rubbish collector.

import gc

Within the following variables, you should enter your community credentials and your dealer IP handle.


For instance, our dealer IP handle is:

Word: learn this tutorial to see learn how to get your dealer IP tackle:

To create an MQTT shopper, we have to get the ESP distinctive ID. That’s what we do within the following line (it’s saved on the client_id variable).

client_id = ubinascii.hexlify(machine.unique_id())

Subsequent, write the subject the ESP#1 is subscribed to, and the subject it is going to be publishing messages:

topic_sub = b’notification’
topic_pub = b’good day’

Then, create the next variables:

last_message = zero
message_interval = 5
counter = zero

The last_message variable will maintain the final time a message was despatched. The message_interval is the time between every message despatched. Right here, we’re setting it to five seconds (this implies a brand new message can be despatched each 5 seconds). The counter variable is just a counter to be added to the message.

After that, we make the procedures to hook up with the community.

station = community.WLAN(community.STA_IF)

station.join(ssid, password)

whereas station.isconnected() == False:

print(‘Connection profitable’)


In the primary.py file is the place we’ll write the code to publish and obtain the messages. Copy the next code to your important.py file.

How the code works

The very first thing it is best to do is making a callback perform that may run each time a message is revealed on a subject the ESP is subscribed to.

Callback perform

The callback perform ought to settle for as parameters the subject and the message.

def sub_cb(matter, msg):
print((matter, msg))
if matter == b’notification’ and msg == b’acquired’:
print(‘ESP acquired hey message’)

In our callback perform, we begin by printing the subject and the message. Then, we verify if the message was revealed on the notification matter, and if the content material of the message is ‘acquired’. If this if assertion is True, it signifies that ESP#2 acquired the ‘hey’ message despatched by ESP#1.

Principally, this callback perform handles what occurs when a sure message is acquired on a sure matter.

Join and subscribe

Then, we’ve got the connect_and_subscribe() perform. This perform is liable for connecting to the dealer in addition to to subscribe to a subject.

def connect_and_subscribe():

Begin by declaring the client_id, mqtt_server and topic_sub variables as international variables. This manner, we will entry these variables all through the code.

international client_id, mqtt_server, topic_sub

Then, create a MQTTClient object referred to as shopper. We have to cross as parameters the cliend_id, and the IP tackle of the MQTT dealer (mqtt_server). These variables have been set beforehand on the boot.py file.

shopper = MQTTClient(client_id, mqtt_server)

After that, set the callback perform to the shopper (sub_cb).


Subsequent, join the shopper to the dealer utilizing the join() technique on the MQTTClient object.


After connecting, we subscribe to the topic_sub matter. Set the topic_sub on the boot.py file (notification).


Lastly, print a message and return the shopper:

print(‘Related to %s MQTT dealer, subscribed to %s matter’ % (mqtt_server, topic_sub))
return shopper

Restart and reconnect

We create a perform referred to as restart_and_reconnect(). This perform can be referred to as in case the ESP32 or ESP8266 fails to hook up with the dealer.

This perform prints a message to tell that the connection was not profitable. We wait 10 seconds. Then, we reset the ESP utilizing the reset() technique.

def restart_and_reconnect():
print(‘Failed to hook up with MQTT dealer. Reconnecting…’)

Obtain and publish messages

Till now, we’ve created features to deal with duties associated with the MQTT communication. Any further, the code will name these features to make issues occur.

The very first thing we have to do is to hook up with the MQTT dealer and subscribe to a subject. So, we create a shopper by calling the connect_and_subscribe() perform.

shopper = connect_and_subscribe()

In case we’re not in a position to hook up with the MQTTT dealer, we’ll restart the ESP by calling the restart_and_reconnect() perform

besides OSError as e:

Within the whereas loop is the place we’ll be receiving and publishing the messages. We use attempt to besides statements to stop the ESP from crashing in case one thing goes flawed.

Contained in the attempt block, we begin by making use of the check_msg() technique on the shopper.


The check_msg() technique checks whether or not a pending message from the server is obtainable. It waits for a single incoming MQTT message and course of it. The subscribed messages are delivered to the callback perform we’ve outlined earlier (the sub_cb() perform). If there isn’t a pending message, it returns with None.

Then, we add an if assertion to checker whether or not 5 seconds (message_interval) have handed because the final message was despatched.

if (time.time() – last_message) > message_interval:

If it’s time to ship a brand new message, we create a msg variable with the “Hiya” textual content adopted by a counter.

msg = b’Good day #%d’ % counter

To publish a message on a sure matter, you simply want to use the publish() technique on the shopper and cross as arguments, the subject and the message. The topic_pub variable was set to good day within the boot.py file.

shopper.publish(topic_pub, msg)

After sending the message, we replace the final time a message was acquired by setting the last_message variable to the present time.

last_message = time.time()

Lastly, we improve the counter variable in each loop.

counter += 1

If one thing sudden occurs, we name the restart_and_reconnect() perform.

besides OSError as e:

That’s it for ESP#1. Keep in mind that you have to add all the subsequent information to make the challenge work (it is best to add the information so as):

  1. umqttsimple.py;
  2. boot.py;
  3. major.py.

After importing all information, it is best to get success messages on: establishing a community connection; connecting to the dealer; and subscribing to the subject.

ESP #2

Let’s now put together ESP#2:

  • It’s subscribed to the howdy matter
  • It publishes on the notification matter

Just like the ESP#1, you additionally have to add the umqttsimple.py, boot.py, and most important.py information.

Importing umqttsimple

To make use of MQTT with the ESP32/ESP8266 and MicroPython, you’ll want to set up the umqttsimple library. Comply with the steps described earlier to put in the umqttsimple library in ESP#2.

You possibly can entry the umqttsimple library code within the following hyperlink:


Copy the next code to the ESP#2 boot.py file.

This code could be very comparable with the earlier boot.py file. You have to exchange the next variables together with your community credentials and the dealer IP tackle.


The one distinction right here is that we subscribe to the good day matter and publish on the notification matter.

topic_sub = b’hey’
topic_pub = b’notification’


Copy the next code to the ESP#2 important.py file.

This code could be very comparable with the primary.py from ESP#1. We create the sub_cb(), the connect_and_subscribe() and the restart_and_reconnect() features. This time, the sub_cb() perform simply prints details about the subject and acquired message.

def sub_cb(matter, msg):
print((matter, msg))

Within the whereas loop, we examine if we acquired a brand new message and reserve it within the new_message variable.

new_message = shopper.check_msg()

If we obtain a brand new message, we publish a message saying ‘acquired’ on the topic_sub matter (on this case we set it to notification within the boot.py file).

if new_message != ‘None’:
shopper.publish(topic_pub, b’acquired’)

That’s it for ESP#2. Keep in mind that you must add all the subsequent information to make the challenge work (you need to add the information so as):

  1. umqttsimple.py;
  2. boot.py;
  3. primary.py.

The ESP32/ESP8266 ought to set up a community connection and hook up with the dealer efficiently.


After importing all the required scripts to each ESP boards and having each boards and the Raspberry Pi with the Mosquitto dealer operating, you’re prepared to check the setup.

The ESP#2 must be receiving the “Good day” messages from ESP#1, as proven within the determine under.

On the opposite aspect, ESP#1 board ought to obtain the “acquired” message. The “acquired” message is revealed by ESP#2 on the notification matter. ESP#1 is subscribed to that matter, so it receives the message.

Wrapping Up

On this easy instance, you’ve discovered how you can trade textual content between two ESP32/ESP8266 boards utilizing MQTT communication protocol. The thought is to make use of the ideas discovered right here to change helpful knowledge like sensor readings or instructions to regulate outputs.

When you like MicroPython with the ESP32/ESP8266, you might also like:

Advisable Assets