"""
Temperature and Humidity Monitor using Raspberry Pi Pico
Hardware: DHT22 Sensor + 16x2 I2C LCD Display
Platform: Wokwi Simulator
Author: MakeMindz
"""
from machine import Pin, I2C
from time import sleep
import dht
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd
# LCD Configuration
I2C_ADDR = 0x27 # I2C address of LCD (default for most I2C LCDs)
I2C_NUM_ROWS = 2 # Number of rows on LCD
I2C_NUM_COLS = 16 # Number of columns on LCD
# Pin Configuration
DHT_PIN = 15 # DHT22 sensor data pin (GPIO 15)
I2C_SDA_PIN = 0 # I2C SDA pin (GPIO 0)
I2C_SCL_PIN = 1 # I2C SCL pin (GPIO 1)
# Initialize I2C for LCD
i2c = I2C(0, sda=Pin(I2C_SDA_PIN), scl=Pin(I2C_SCL_PIN), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)
# Initialize DHT22 sensor
sensor = dht.DHT22(Pin(DHT_PIN))
# Startup message
lcd.clear()
lcd.putstr("MakeMindz")
lcd.move_to(0, 1)
lcd.putstr("Temp & Humidity")
sleep(2)
print("Temperature and Humidity Monitor Started!")
print("=" * 40)
def celsius_to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit"""
return (celsius * 9/5) + 32
def read_sensor():
"""Read temperature and humidity from DHT22 sensor"""
try:
sensor.measure()
temp_c = sensor.temperature()
humidity = sensor.humidity()
return temp_c, humidity
except OSError as e:
print(f"Failed to read sensor: {e}")
return None, None
def display_readings(temp_c, humidity):
"""Display temperature and humidity on LCD"""
if temp_c is not None and humidity is not None:
# Convert to Fahrenheit
temp_f = celsius_to_fahrenheit(temp_c)
# Clear LCD
lcd.clear()
# Line 1: Temperature
lcd.putstr(f"Temp:{temp_c:.1f}C")
lcd.move_to(0, 1)
# Line 2: Humidity
lcd.putstr(f"Humid:{humidity:.1f}%")
# Print to console
print(f"Temperature: {temp_c:.1f}°C ({temp_f:.1f}°F)")
print(f"Humidity: {humidity:.1f}%")
print("-" * 40)
else:
# Display error message
lcd.clear()
lcd.putstr("Sensor Error!")
lcd.move_to(0, 1)
lcd.putstr("Check Wiring")
print("Error: Could not read sensor data")
# Main loop
while True:
try:
# Read sensor data
temperature, humidity = read_sensor()
# Display on LCD and console
display_readings(temperature, humidity)
# Wait 2 seconds before next reading
sleep(2)
except KeyboardInterrupt:
print("\nProgram stopped by user")
lcd.clear()
lcd.putstr("Program Stopped")
break
except Exception as e:
print(f"Error in main loop: {e}")
lcd.clear()
lcd.putstr("System Error!")
sleep(2)