"""
MicroPython MQTT OLED SSD1306 Example for Wokwi.com
To control the OLED:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Public, set the Topic to "wokwi"
4. in the Message field type "Bye" (or any other str)
5. click "Publish"
"""
import network
import ujson
from machine import Pin, I2C
import ssd1306
from time import sleep
from umqtt.simple import MQTTClient
# ESP32 Pin assignment
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.text('Hello, Wokwi!', 10, 10)
oled.show()
oled.fill(0) # clear display
def mqtt_message(topic, msg):
print("Incoming message:", msg)
try:
msg = ujson.loads(msg)
oled.text(msg, 10, 10)
oled.show()
sleep(2)
oled.fill(0)
except Exception as e:
print("Error:", e)
#
print("Connecting to WiFi...", end="")
import network
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "")
while not wifi.isconnected():
sleep(0.5)
print(".", end="")
print("Done")
print("Connecting to MQTT...")
client = MQTTClient("wokwi1", "broker.hivemq.com")
client.set_callback(mqtt_message)
client.connect()
client.subscribe("wokwi")
print("Connected!")
while True:
client.wait_msg()