from machine import I2C, Pin
from time import sleep
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import network
from umqtt.simple import MQTTClient
# Wi-Fi credentials and MQTT broker details
ssid = 'Wokwi-GUEST'
password = '' # Optional password
mqtt_server = 'broker.emqx.io'
client_id = 'esp32_11231hq'
topic_sub = 'temperature-data' # Subscription topic
# Initialize I2C for the LCD
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000) # GPIO 22 as SCL and GPIO 21 as SDA
lcd = I2cLcd(i2c, 0x27, 2, 16) # Configure the LCD with address 0x27, 2 rows, 16 columns
# Connect to Wi-Fi
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
# Wait for the Wi-Fi connection
while not station.isconnected():
lcd.clear()
lcd.putstr('Connecting to\nWi-Fi...')
print('Connecting to Wi-Fi...')
sleep(1)
lcd.clear()
lcd.putstr('Wi-Fi Connected!')
print('Connected to Wi-Fi')
# Function to connect to the MQTT broker
def connect_mqtt():
client = MQTTClient(client_id, mqtt_server)
client.connect()
print('Connected to MQTT broker')
lcd.clear()
lcd.putstr("MQTT Connected!")
return client
# Callback to handle incoming messages
def on_message(topic, msg):
print(f"Received message: {msg.decode()} on topic: {topic.decode()}")
lcd.clear()
lcd.putstr(f"Temp: {msg.decode()}")
# Connect to the MQTT broker and subscribe to the topic
client = connect_mqtt()
client.set_callback(on_message)
# Subscribe to the temperature data topic
client.subscribe(topic_sub)
print(f"Subscribed to topic: {topic_sub}")
lcd.clear()
lcd.putstr(f"Subscribed to\n{topic_sub}")
# Main loop to keep checking for messages
try:
while True:
client.check_msg() # Check for new messages
sleep(1) # Short delay to avoid overloading the broker
except KeyboardInterrupt:
print("Disconnecting...")
client.disconnect()