# main.py – DHT22 Weather Station with OLED Display on Raspberry Pi Pico W
from machine import Pin, I2C
import time
import dht
from ssd1306 import SSD1306_I2C
# --- Pin Configuration ---
DHT_PIN = 15
sensor = dht.DHT22(Pin(DHT_PIN))
# --- I2C Configuration for OLED (change pins if needed) ---
i2c = I2C(1, scl=Pin(27), sda=Pin(26), freq=400000)
oled = SSD1306_I2C(128, 64, i2c)
# --- Function to Read DHT22 Safely ---
def read_dht22():
for _ in range(3):
try:
sensor.measure()
t = sensor.temperature()
h = sensor.humidity()
if -40 <= t <= 80 and 0 <= h <= 100:
return t, h
except OSError:
pass
time.sleep(1)
return None, None
# --- Function to Display Data on OLED ---
def display_data(temp, hum):
oled.fill(0) # Clear screen
oled.text(" WEATHER STATION ", 0, 0)
oled.text("----------------", 0, 10)
oled.text("Temp: {:.1f} C".format(temp), 0, 25)
oled.text("Hum : {:.1f} %".format(hum), 0, 40)
# Simple status messages
if temp > 35:
oled.text("HOT!", 90, 25)
elif temp < 18:
oled.text("COLD", 90, 25)
oled.show()
# --- Main Loop ---
while True:
temp, hum = read_dht22()
if temp is not None and hum is not None:
print("Temperature: {:.1f}°C Humidity: {:.1f}%".format(temp, hum))
display_data(temp, hum)
else:
print("⚠️ Sensor reading failed!")
oled.fill(0)
oled.text("Sensor Error!", 10, 25)
oled.show()
time.sleep(3)