import time
import dht
from machine import Pin, PWM, I2C
from i2c_lcd import I2cLcd
# Setup
sensor = dht.DHT22(Pin(15))
red = Pin(16, Pin.OUT)
green = Pin(17, Pin.OUT)
blue = Pin(18, Pin.OUT)
servo = PWM(Pin(19)); servo.freq(50)
i2c = I2C(0, scl=Pin(1), sda=Pin(0))
lcd = I2cLcd(i2c, 0x27, 2, 16)
def set_rgb(r, g, b):
red.value(r); green.value(g); blue.value(b)
print("RGB set to:", r, g, b, "— Pin states:", red.value(), green.value(), blue.value())
def servo_angle(angle):
angle = max(0, min(180, angle)) # Clamp angle to 0–180
# Wokwi expects pulses between ~1.0ms (0°) and ~2.0ms (180°)
min_duty = int((1.0 / 20) * 65535) # 3276 for 1.0ms
max_duty = int((2.0 / 20) * 65535) # 6553 for 2.0ms
duty = int(min_duty + (max_duty - min_duty) * angle / 180)
servo.duty_u16(duty)
lcd.clear()
lcd.putstr("Weather Station")
time.sleep(2)
while True:
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
print(f"\nReading → Temp: {temp:.1f}C, Hum: {hum:.1f}%")
# Servo + LED control
if temp < 20:
servo_angle(0); set_rgb(0,0,1)
elif temp > 30:
servo_angle(180); set_rgb(1,0,0)
else:
servo_angle(90); set_rgb(0,1,0)
# Display values
lcd.move_to(0,0); lcd.putstr(f"Temp: {temp:.1f} C ")
lcd.move_to(0,1); lcd.putstr(f"Hum: {hum:.1f} % ")
except Exception as e:
print("Error:", e)
lcd.clear(); lcd.putstr("Error"); set_rgb(1,0,0)
time.sleep(5)