Introduction

Implementing MQTT in ESP8266 with MicroPython

In this blog post, we’re going to discuss how to set up MQTT on the ESP8266 using MicroPython. We’ll walk you through the steps of setting up MQTT and subscribe to a topic in Pub-Sub Model, and then give you a few code samples to get started. So if you’re looking for a way to get your IoT projects up and running quickly, read on!

The new Espressif Systems 8266 series of Wi-Fi chips is a powerful and versatile module. It features an integrated Tensilica microcontroller, 2 GHz wireless connectivity with antenna support for longer range connections as well it has power management modules that allow you to use less battery in your IoT devices! This makes them perfect candidate if you’re looking at creating some low consumption gadget prototypes or full blown sized gadgets without having too many external components attached.

What is MQTT

Fig. 2 MQTT Protocol
  • MQTT is a protocol to communicate IoT messages and publish data to an IoT server or MQTT broker.
  • MQTT stands for Message Queuing Telemetry Protocol. As the name suggests, it is a communication/messaging protocol for IoT applications. It is a Publish and Subscribe protocol to communicate data between the internet-enabled devices.
  • A broker is a kind of handler or acts as an interface medium between the publisher device or transmitter and the subscriber device that is the receiver. The broker’s role is to handle or filter all the incoming data from the publisher and distribute them to the subscribers in the most efficient way.

Role of a broker in MQTT protocol:

  • Receiving data or messages from the publisher or transmitter (i.e., ESP32)
  • Filtering the received data.
  • Determining the interested subscriber in each information packet or message.
  • Forwarding the data to the interested subscriber or receiver device.

There are multiple brokers available to handle and distribute the information and in this tutorial, we are using the ThingSpeak as an MQTT broker.

Hardware and Software requirements:

  1. ESP8266 development board
  2. uPyCraft IDE
  3. MQTT broker

Installing uPyCraft IDE for MicroPython programming in ESP8266 (Windows)

To program the ESP8266 using the Micropython firmware, it is recommended to use either uPyCraft IDE or Thonny IDE. In this tutorial, we are using the uPyCraft IDE.

Note: Before installing the uPyCraft IDE it is required to install the latest version of Python.

Installing Python (Windows PC)

Follow the link to download the Python installation file. https://www.python.org/downloads/

Fig. 3 Download Python
  • Once the Python installation file is downloaded successfully. Open the file.
  • Enable the Add Python 3.10 to Path at the bottom and click on Install Now.
  • Click ‘OK’  once it is installed successfully.

Installing uPyCraft IDE

Click on the link to download uPyCraft IDE: https://github.com/DFRobot/uPyCraft/blob/master/uPyCraft_V1.0.exe

Flashing MicroPython firmware for ESP8266 into ESP8266 development board:

Follow the link to download the MicroPython firmware for ESP8266: https://micropython.org/download/

Download ESP8266 Firmware

  • Open the uPyCraft IDE.
  • Go to Tools, select the Serial Port. Then select the development board you are going to use i.e., ESP8266.

Burn Firmware

  • Select the firmware properties for ESP8266 as shown below.
Fig. 6 Set properties to Burn Firmware
  • Select the downloaded ESP8266 firmware file to upload or burn into ESP8266.

Fig. 7 Select ESP8266 Firmware

  • After clicking on OK to burn the firmware, press the Flash button from the ESP8266 development board till the Erase Flash progresses 100%. After that, you can release the flash button and wait till the Burn process completes.

Fig. 8 Erase Flash and burn micropython firmware.

  • Now your uPyCraft IDE is ready to work with the ESP8266 module.

ThingSpeak (MQTT Broker)

It is an open-source software or data platform for the Internet of Things (IoT) applications to communicate data between internet-enabled devices. ThingSpeak is a web service operated by The MathWorks that can send sensor readings or data to the cloud. You can also visualize and manipulate (calculate the data) the data sent from the device to ThingSpeak. Data can be stored on either private or public channels. ThingSpeak is commonly used for IoT prototyping and proof-of-concept systems that require analysis.

Getting started with ThingSpeak

  • The first step is creating a MathWorks account. Click on the given link to create an account: https://thingspeak.com
Fig. 9 Getting started with ThingSpeak
  • Enter your required information to create a MathWorks account as shown below:

Create MathWorks account

  • Click on Sign in, if you already have a MathWorks account.
Fig. 11 MathWorks Sign in
  • Create a new channel by clicking on the given ‘New Channel’ icon. 
Fig. 12 New Channel
  • Enter the respective details in the channel.
  • Here we are creating a channel named ‘ESP8266 MQTT’ and creating only one field that is to store or represent the continuously increasing integer value.
  • You can also enable or use more than one field as per your requirements.
Fig. 13
  • Finally, click on the ‘save channel’ to save the channel details/information.
Fig. 14 save the channel
  • A new window will open containing the channel details and Channel Stats once the channel is created successfully.
  • The channel will be automatically updated with the new data, every time the sender publishes some data to the broker.

Programming ESP8266 with uPyCraft 

  • Adding umqttsimple library file
  • Go to File >> New.
  • Paste the code in uPyCraft IDE and save it as umqttsimple.py.
# Load necessary libraries
import machine
import network
import sys
try:
  from umqttsimple import MQTTClient
except:
  print("error with the umqttsimple file")
from machine import Pin
import time


# **************************************#
# Objects:
led = machine.Pin(2,machine.Pin.OUT)

# Network settings
wifi_ssid = "public"
wifi_password = "[email protected]"

# Create a station object to store our connection
station = network.WLAN(network.STA_IF)
station.active(True)

# Continually try to connect to WiFi access point
while not station.isconnected():

    # Try to connect to WiFi access point
    print("Connecting...")
    station.connect(wifi_ssid, wifi_password)

  
# Continually print out HTML from web page as long as we have a connection
while not station.isconnected():

    # Display connection details
    try:
      print("Connected!")
      print("My IP Address:", station.ifconfig()[0])
    except:
      print("couldn't connect")
    
# If we lose connection, repeat this main.py and retry for a connection
print("Connection lost. Trying again.")

# **************************************#
# Global variables and constants:
SERVER = "mqtt.thingspeak.com"
client = MQTTClient("umqtt_client", SERVER)
CHANNEL_ID = "1657034"
WRITE_API_KEY = "2PNCBTOXL7TL2NO9"
# topic = "channels/1249898/publish/PJX6E1D8XLV18Z87"
topic = "channels/" + CHANNEL_ID + "/publish/" + WRITE_API_KEY
UPDATE_TIME_INTERVAL = 5000 # in ms unit
last_update = time.ticks_ms()

# **************************************
# Main loop:
try:
  while True:
    if time.ticks_ms() - last_update >= UPDATE_TIME_INTERVAL:
      for t in range(0, 1000, 2):
        print(t)

        #payload = "field1=" + str(t) + "&field2=" + str(h)
        payload = "field1={}" .format(str(t))

        client.connect()
        client.publish(topic, payload)
        client.disconnect()

        print(payload)
        led.value(not led.value())
        last_update = time.ticks_ms()
  
except:
  print("error while dealing with server")

MicroPython Code to implement MQTT with ESP8266

Code Description

  • The first step is importing or adding the necessary libraries.
Fig. 15 Adding Library files

Next is creating an object to define the GPIO pin to which LED is connected and set the mode as output.

Fig. 16 Objects
  • Enter the Wi-Fi credentials for internet connectivity.
Fig. 17 Network Credentials
  • Next you need to configure the ESP8266 in station mode and create an object to store the connection.
Fig. 18 Station object
  • ESP8266 is continuously trying to connect with the Wi-Fi network using the provided network credentials.
  • Once the ESP8266 module has successfully established a connection with the Wi-Fi, print the respective result along with the IP address of the device.
  • Next step is defining the global variables and constants.
  • Enter the details like the server address, API_key, Channel ID etc. of the channel you have created on the ThingSpeak server.
Fig. 21 Enter the broker details

Main Loop

  • Inside the main loop, we are going to publish the data to the MQTT broker that is the ThingSpeak server.
  • Here we are using a for loop to continuously increase the integer value (or you can share some sensor readings) stored inside a variable ‘t’, till the value of ‘1000’.
  • The final step is connecting to the MQTT client and continuously publishing the data or sensor readings to the ThingSpeak MQTT broker using client.publish function.
  • The broker will be updated with new data in every 5sec or 5000ms.
  • LED will blink with every message update.
Fig. 22 Publish the data to the MQTT broker (ThingSpeak server)

Testing

  • Save the program with the .py extension.
Fig. 22 Save the program
  • Select the right serial port to upload the code into ESP8266.
Fig. 23 Select the COM port
Fig. 24 development board.
  • Now click on the download and run icon.
  • Open the MQTT broker or thingspeak server. 
  • The server should be updated with the integer values as per the code instruction.
  • An image has been attached below for your reference:
Fig. 25 MQTT broker (ThingSpeak server)

Wrapping it up

This concludes our tutorial, about how to implement MQTT on ESP8266 using MicroPython. If you want to implement MQtt on ESP32 please follow this article: Getting Started with Mqtt on ESP32 | MicroPython

0 0 votes
Article Rating
Previous articleHow to Interface Raspberry Pi Pico with GPS | SparkFun SAM-M8Q
Next articleHow to Interface Raspberry Pi Zero with GPS | SparkFun SAM-M8Q
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments