Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

NO.1
wifi+mqtt

To display the corresponding data without using sensors

It is necessary to prioritize obtaining and visualizing data from the network (connect to WiFi and request API) (LVGL)

Several MQTT libraries were used, and finally, micropython-mqtt was chosen

Reference article

MicroPython[ESP32-S3]: Setting up MQTT connection with micropython-mqtt

GitHub address

https://github.com/peterhinch/micropython-mqtt/tree/master

This is an alternative to the official driver. It has been tested on the following platforms.

  • ESP8266

  • ESP32, ESP32-S2, and ESP32-S3

  • pyboard D

  • Arduino Nano Connect

  • Raspberry Pi Pico W

The main features of this driver are:

  • Non-blocking operation for applications using uasyncio.

  • Automatic recovery from WiFi and proxy interruptions.

  • True QoS == 1 operation with retransmission.

  • Improved WiFi range due to tolerance for bad connections.

Notes

It requires entering WiFi and MQTT accounts during initialization, both need to be connected simultaneously

When used on ESP32S3, it is considered that it does not handle module coupling well

When used on the small yellow board, it is found to be just right for the wifi+mqtt scenario

NO.2
Transfer MQTT library files to ESP32

Need to download the mqtt_as.py library and transfer it to ESP32

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

Click Thonny, File – Open

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

Select This Computer

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

Select the downloaded mqtt_as.py

Click Open

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

After opening the corresponding file, click File again, Save As

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

Click MicroPython Device

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

You can see the current MicroPython files

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

Enter the file name to save, such as mqtt_as.py

Remember to include the file extension

Click OK

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

Wait for the save to complete

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

Click Thonny again, File, Open, select MicroPython device

You can see the newly added file besides boot.py, and it shows the file size

This indicates that the file was saved successfully

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

NO.3
Connecting WiFi + MQTT

Connection code, also reference article

MicroPython[ESP32-S3]: Setting up MQTT connection with micropython-mqtt

Dependencies introduced in the code

from mqtt_as import MQTTClient, config
import uasyncio as asyncio

Then use the provided API to connect to WiFi and MQTT

# Local configuration
config['ssid'] = 'wifi name'
config['wifi_pw'] = 'wifi password'
config['server'] = 'mqtt ip addr'

# Listen for message reception
def dsx2020_call(topic, msg, retained):
    print("Message received")
    topic_str=topic.decode()
    msg_str=msg.decode()
    print("topic_str",topic_str)
    print("msg_str",msg_str)

# Subscribe to topics
async def conn_han(client):
    await client.subscribe('dsx2020', 1)
    await client.subscribe('weather', 1)

# Initialize
async def main(client):
    await client.connect()
    n = 0
    while True:
        await asyncio.sleep(5)
        try:
            print('Change every 5 seconds', n)
        except:
            print("err")
        n += 1

# Set callback function
config['subs_cb'] = dsx2020_call
# Set subscription topics
config['connect_coro'] = conn_han

# Instantiate
MQTTClient.DEBUG = True
client = MQTTClient(config)
try:
    asyncio.run(main(client))
finally:
    client.close()

Actual effect test

Click Run to run the current script

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

Check the console

You can see that it first tries to monitor WiFi quality and connect

Then connects to MQTT

Then executes log every 5 seconds

When I refresh my website and send an MQTT topic message, the corresponding ESP32 will receive the MQTT message and display the current message content, such as website online, website offline, etc.

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

Notes

At this time, the demonstration did not light up the screen, so the wifi+mqtt function was successful

However, once the screen is lit, trying to connect to wifi+mqtt will prompt insufficient memory and other issues

NO.4
Light up the screen + connect to wifi + mqtt

Reference article

ESP32 Development Board TFT Touch Screen (Small Yellow Board) [MicroPython]: Flashing MicroPython + LVGL firmware and demonstration

The article lights up the screen and displays basic text hello world

This article attempts to light up the screen, display text, and then connect to wifi + mqtt to see if the function is stable and throws errors

In fact, the screen can light up and display text normally, but it reports an error when connecting to WiFi

Traceback (most recent call last):
  File "<stdin>", line 75, in <module>
  File "uasyncio/core.py", line 1, in run
  File "uasyncio/core.py", line 1, in run_until_complete
  File "<stdin>", line 56, in main
  File "mqtt_as.py", line 637, in connect
  File "mqtt_as.py", line 294, in _connect
  File "mqtt_as.py", line 233, in _as_write
OSError: [Errno 113] ECONNABORTED

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

Searching for OSError: [Errno 113] ECONNABORTED in the search engine did not yield corresponding answers

Previous articles hinted at the reason

MicroPython[ESP32]: MQTT message subscription and publishing and disconnection notification

When ESP32 uses lvgl and mqtt and http simultaneously, it can cause process blocking or restart due to insufficient memory allocation

It will prompt

  • memory allocation failed, allocating 12300 bytes

  • Not enough DMA-able memory to allocate display buffer

This is also the reason why the learning direction changed to ESP32S3, giving up on ESP32

NO.5
Adjusting Order

Connect to wifi + mqtt first

After successful connection, wait 3 seconds and then light up the screen (light up the screen when n=1)

# Initialize
async def main(client):
    await client.connect()
    
    n = 0
    while True:
        await asyncio.sleep(5)
        if n==1:
            init_scrren()
        try:
            print('Change every 5 seconds', n)
        except:
            print("err")
        n += 1

You can see that there are no errors thrown, and it is running normally

Similarly, micropython-mqtt will prompt the current memory

RAM free 79904 alloc 28128 (Free memory 79KB, Allocated memory 28KB)

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

NO.6
Tips

A hotspot has been set up, scan the code to connect

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

WeChat scan code

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

Network configuration successful and connected to MQTT successfully

Connecting WiFi and MQTT with ESP32 TFT Touch Screen Development Board (MicroPython)

Applicable for distributing network configuration users

If it is for personal use, just write the WiFi and password directly in the code

END

If you find this article helpful, please give a thumbs up and bookmark it , see you next time.

Recommended Reading

《ESP32 Development Board TFT Touch Screen (Small Yellow Board) [MicroPython]: Flashing MicroPython + LVGL firmware and demonstration》

《ESP32 Development Board TFT Touch Screen (Small Yellow Board) [MicroPython]: Example Demo flashing firmware, testing screen display and touch》

《ESP32 Development Board TFT Touch Screen (Small Yellow Board) [MicroPython]: Simple record of integrated development board features and usage scenarios》

☕ Friends, you have seen this, are you sure you don’t want to follow? 👇

Leave a Comment

×