from machine import Pin, SoftI2C
import dht
import time
from i2c_lcd import I2cLcd
import network
from umqtt.simple import MQTTClient
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# MQTT settings
MQTT_CLIENT_ID = ""
MQTT_BROKER = "test.mosquitto.org"
MQTT_PORT = 1883
MQTT_USER = "" # Leave empty if no authentication is needed
MQTT_PASSWORD = "" # Leave empty if no authentication is needed
MQTT_TOPIC_TEMPT = "farm temperature"
MQTT_TOPIC_HUMIDITY = "farm humidity"
# Connect to WiFi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
time.sleep(1)
print("Connected to WiFi")
# Connect to MQTT broker
def connect_mqtt():
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.connect()
print("Connected to MQTT Broker")
return client
# Initialize LCD and sensor
led = Pin(5, Pin.OUT)
sensor = dht.DHT22(Pin(14))
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=100000) # Adjusted frequency to 100000 for better compatibility
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
lcd.putstr("Hello")
print("Initial message displayed")
# Connect to WiFi
connect_wifi()
# Connect to MQTT broker
client = connect_mqtt()
humi = -1
temp = -1
while True:
sensor.measure() # Read the parameters from the sensor
new_temp = sensor.temperature()
new_humi = sensor.humidity()
print("Temperature:", new_temp, "°C")
print("Humidity:", new_humi, "%")
# Display temperature
if temp != new_temp:
temp = new_temp
lcd.move_to(0, 0)
lcd.putstr(" ")
lcd.move_to(0, 0)
lcd.putstr("Temp: ")
lcd.putstr(str(temp))
print("Temperature updated on LCD")
# Publish temperature to MQTT
client.publish(MQTT_TOPIC_TEMPT, str(temp))
print("Temperature published to MQTT")
# Display humidity
if humi != new_humi:
humi = new_humi
lcd.move_to(0, 1)
lcd.putstr(" ")
lcd.move_to(0, 1)
lcd.putstr("Humidity: ")
lcd.putstr(str(humi))
print("Humidity updated on LCD")
# Publish humidity to MQTT
client.publish(MQTT_TOPIC_HUMIDITY, str(humi))
print("Humidity published to MQTT")
# Control LED based on temperature
if temp > 24:
led.on() # Turn on LED if temperature is over 24°C
else:
led.off()
time.sleep(1) # Delay for stability