import time
from umqtt_simple import MQTTClient
import network
import ujson
from machine import Pin, I2C
from pico_i2c_lcd import I2cLcd
# Define MQTT connection information
mqtt_server = "broker.mqttdashboard.com"
mqtt_port = 1883
mqtt_topic = "iot/data" # The MQTT topic to subscribe to
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST", "")
print("Connecting to Wi-Fi...")
while not wlan.isconnected():
time.sleep(1)
print("Wi-Fi connected")
# Variables to store the latest values
latest_mode = "unknown"
latest_temp = 0.0
latest_hum = 0.0
latest_servo = "0"
latest_led = 0
latest_soilsensor = 0
def on_message(topic, msg):
global latest_mode, latest_temp, latest_hum, latest_servo, latest_led, latest_soilsensor
try:
# Parse the JSON message
message_data = ujson.loads(msg)
# Access the 'payload' field in the message_data dictionary
payload_data = message_data.get('payload', {})
# Access specific values in the payload
latest_mode = payload_data.get('mode', 'unknown')
latest_temp = payload_data.get('temp', 0.0)
latest_hum = payload_data.get('hum', 0.0)
latest_servo = payload_data.get('servo', '0')
latest_led = payload_data.get('led', 0)
latest_soilsensor = payload_data.get('soilsensor', 0)
except Exception as e:
print("Error parsing message:", e)
# Wi-Fi connection
connect_to_wifi()
# MQTT client setup
client = MQTTClient("raspberry-pi", mqtt_server, port=mqtt_port)
def connect_to_mqtt():
print("Connecting to MQTT...")
while client.connect() != 0:
print("MQTT connection failed. Retrying in 5 seconds...")
time.sleep(5)
print("MQTT connection successful")
client.set_callback(on_message)
connect_to_mqtt()
# Subscribe to the MQTT topic
client.subscribe(mqtt_topic)
# Initialize the I2C bus and LCD
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000) # Adjust the pins and frequency as needed
lcd = I2cLcd(i2c, 0x27, 2, 16) # Adjust the address and LCD dimensions as needed
try:
while True:
# Display the latest values on the LCD
lcd.move_to(0, 0)
lcd.putstr("Mode: " + latest_mode)
lcd.move_to(0, 1)
lcd.putstr("Temp: {:.2f} C".format(latest_temp))
lcd.move_to(0, 2)
lcd.putstr("Humidity: {:.2f}%".format(latest_hum))
lcd.move_to(0, 3)
lcd.putstr("Servo: " + latest_servo)
lcd.move_to(0, 4)
lcd.putstr("LED: {}".format(latest_led))
lcd.move_to(0, 5)
lcd.putstr("Soil Sensor: {}".format(latest_soilsensor))
time.sleep(1) # Delay for a while before updating the LCD again
except KeyboardInterrupt:
client.disconnect()