Introduction

ESP32 MQTT with MicroPython Programming

The ESP32 is a system-on chip (SoC) that comes with an array of inbuilt features. It’s capable for performing all tasks related to the IoT: sensing, processing data and displaying/storing it while also transmitting this information via Wi-Fi or Bluetooth Low Energy protocols! This makes them perfect candidates when looking into building connected devices such as those found within today’s modern cars which have sensors attached allowing drivers access live traffic updates without changing any settings on their own phone

The IoT (or Internet of Things) is a network of interconnected computing devices like automobiles, digital machines with inbuilt sensors and each with a unique identifier along with the ability of communicate data over a network without any human intervention.

In this article, we will learn how to program ESP32 and implement MQTT protocol using MicroPython programming language. We will publish the Hall sensor readings/values from ESP32 to ThingSpeak over the MQTT protocol.

What is MQTT?

Message Queue Telemetry Transport is a communication/messaging protocol for IoT applications. It is a Publish and Subscribe based Advance Message Queue Protocol(AMQP) to communicate data between the internet enabled devices.

Why MQTT?

Well there are plenty of AMQP’s available, Rabbit-MQ is also a famous one.. and this is used in many micro-services based applications, ZeroMQ is also very light weight and ultrafast MQ. While writing this blog, I am thinking on porting and testing ZeroMQ. However None the less MQTT found its way into IoT applications primarily to provide cloud connectivity for IoT devices.

What is MQTT Broker?

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.

Fig. 1 MQTT Protocol

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.

Hall Effect Sensor

The ESP32 module offers some inbuilt sensors and the Hall Effect sensor is one of them. It is a transducer that responds with a change in its Hall voltage (or output voltage) when placed in a magnetic field.

The Hall-effect comes into existence when the magnetic field makes the current (flowing inside a conductor) deviate from its path. 

Software and Hardware requirements

  • uPyCraft IDE
  • MQTT Broker (ThingSpeak)
  • ESP32 development board.

Installing uPyCraft IDE for MicroPython programming in ESP32 (Windows)

To program the ESP32 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.

Fig. 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

Fig. uPyCraft IDE
  • Flashing the MicroPython firmware to ESP32 module:

Whether you are using the ESP32 or ESP8266, for each module it is required to install the Micropython firmware into ESP32 (because MicroPython is not flashed into the ESP32 by default).

Fig. ESP32

  • Click on the .bin file to download the ESP32 micropython firmware.
Fig. ESP32 MicroPython Firmware

Fig. ESP32 MicroPython Firmware

  • Open the uPyCraft IDE. 
  • Go to Tools and click on Burn Firmware. 
Fig. Burn Firmware.
  • Select the properties as shown below.

Fig.

  • Click on Choose  and select the downloaded ESP32 MicroPython firmware that is the ‘.bin’ file.

Fig.

  • Click on Open.
  • Then Click on OK.
  • Press the EN button form ESP32.
  • Now your uPyCraft IDE is ready to program.

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. 2 Getting started with ThinSpeak

Fig. 2 Getting started with ThinSpeak

  • Enter your required information to create a MathWorks account as shown below:

Fig. 3 Creating MathWorks account

  • If you have already created a MathWorks account, then click on Sign in.

Fig.  4 MathWorks Sign in

  • Create a new channel by clicking on the given ‘New Channel’ icon. 

Fig. 4 New Channel

  • Enter the respective details in the channel.
  • We have already mentioned, that we are using the ESP32’s inbuilt sensor (hall effect sensor) for sensor readings and those readings will be published to the ThingSpeak server (the MQTT broker).
  • Here we are creating a channel named ‘ESP32 MQTT’ and creating only one field that is to store or represent the hall value.
  • You can also enable or use more than one field as per your requirements.

.

Fig. 5 Enter the details in the channel

  • Finally, click on the ‘save channel’ to save the channel details/information.

Fig. 6 save the channel

  • A new window will open containing the channel details and Channel Stats once the channel is created successfully.

Programming ESP32 with uPyCraft IDE

As mentioned earlier, in this tutorial we are using the uPyCraft IDE to compile and upload the code into the ESP32 development board.

Source Code

# Load necessary libraries
import machine
import network
import sys
from umqtt.simple import MQTTClient
import time


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


# **************************************#
# Network settings
wifi_ssid = "SSID"
wifi_password = "PASSWORD"

# 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
    print("Connected!")
    print("My IP Address:", station.ifconfig()[0])
    
    # Check to see if our REPL button is pressed over 10 seconds
    for i in range(100):
        if repl_button.value() == 0:
            print("Dropping to REPL")
            repl_led.value(1)
            sys.exit()
        utime.sleep_ms(100)

# 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 = "replace this with you channel ID"
WRITE_API_KEY = "enter you write API key"
# 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:
while True:
    if time.ticks_ms() - last_update >= UPDATE_TIME_INTERVAL:
        t = esp32.hall_sensor()
        print("Hall Value")
        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()

Code Description

  • The first step is importing the required libraries.
Fig. 7  importing required libraries
  • Next step is creating an object to define the GPIO pin to which LED is connected and set the mode as output.
Fig. 8 Objects
  • Enter the Wi-Fi credentials for internet connectivity.
Fig. 9 Network Credentials
  • Next you need to configure the ESP32 in station mode and create an object to store the connection.
Fig. 10 Station object

  • ESP32 is continuously trying to connect with the Wi-Fi network using the provided network credentials.
Fig. 11

  • Once the ESP32 module has successfully established a connection with the Wi-Fi, print the respective result along with the IP address of the device.
Fig. 12
  • 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. 13 Enter the broker details

  • Inside the main loop, a variable ‘t’ is used to store the hall sensor values which are to be published over the MQTT protocol.
Fig. 14

  • The final step is connecting to the MQTT client and continuously publishing the data or sensor readings to the ThingSpeak MQTT broker.
  • LED will blink with every message update.
Fig. 15 Connecting to the client

  • Testing
  • Save the code you have written.
Fig. 16save the code

Fig. 16save the code

  • Select the right COM port to upload the code into ESP32.
Fig. 17 Select the COM port
  • Select the correct development board you are using.
Fig. 18 Select the development board

  • Burn the code into the ESP32 development board.
Fig. 19 Burn Firmware

  • Turn ON the source Wi-Fi to which ESP32 is supposed to connect.
  • Then open the ThingSpeak MQTT broker to see the published data. A screenshot has been attached below for your reference:
Fig. 20 ThingSpeak server

This concludes the tutorial, we hope you found this for some help.

0 0 votes
Article Rating
Previous articleHow to Interface ESP32 with AdaFruit LoRa RFM69HCW
Next articleHow to Interface Raspberry Pi Pico with AdaFruit LoRa
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments