from machine import I2C, Pin, PWM
from time import sleep
from pico_i2c_lcd import I2cLcd
import dht
# DHT22 sensor setup
dSensor = dht.DHT22(Pin(0)) # Adjust the pin as needed
# LED Pins setup
red_led = Pin(16, Pin.OUT)
green_led = Pin(15, Pin.OUT)
yellow_led = Pin(17, Pin.OUT)
# Buzzer setup
buzzer = PWM(Pin(28, Pin.OUT))
# Buzzer control functions
def beep(frequency, duration):
buzzer.freq(frequency)
buzzer.duty_u16(32768) # Set duty cycle for volume (approx. 50%)
sleep(duration)
buzzer.duty_u16(0) # Turn buzzer off
def alert_beep():
for _ in range(10): # Repeat for emphasis
beep(980, 0.5) # High-pitched beep
sleep(0.2)
# I2C LCD initialization
def initialize_i2c_lcd(sda_pin, scl_pin, i2c_freq):
"""Initialize the I2C LCD display with the given parameters."""
i2c_bus = I2C(0, sda=Pin(sda_pin), scl=Pin(scl_pin), freq=i2c_freq)
i2c_address = i2c_bus.scan()[0] # Find the I2C address
lcd = I2cLcd(i2c_bus, i2c_address, 2, 16)
lcd.clear()
lcd.blink_cursor_off()
return lcd, i2c_address, i2c_bus
# Read DHT22 data
def read_dht():
"""Read temperature and humidity from the DHT sensor."""
try:
dSensor.measure()
temp = dSensor.temperature()
temp_f = (temp * (9/5)) + 32.0
hum = dSensor.humidity()
return temp, hum
except OSError as e:
print('Failed to read data from DHT sensor')
return None, None
# Display data on the LCD
def print_dht_data(lcd, i2c_bus):
"""Display temperature and humidity on the LCD."""
temp, hum = read_dht()
if temp is not None and hum is not None:
lcd.clear()
lcd.putstr("Temp:")
lcd.putstr(str(int(temp)) + "C")
lcd.putstr("\nHumidity:")
lcd.putstr(str(int(hum)) + "%")
sleep(1) # Delay to reduce flickering
# Main program loop
def main():
lcd_display, i2c_address, i2c_bus = initialize_i2c_lcd(sda_pin=4, scl_pin=1, i2c_freq=400000)
while True:
temp, hum = read_dht()
if temp is not None and hum is not None:
if temp < 28:
green_led.on()
yellow_led.off()
red_led.off()
buzzer.duty_u16(0) # Ensure buzzer is off
elif 28 <= temp < 37:
green_led.off()
yellow_led.on()
red_led.off()
buzzer.duty_u16(0) # Ensure buzzer is off
else: # temp >= 37
green_led.off()
yellow_led.off()
red_led.on()
alert_beep() # Trigger alert beeps
print_dht_data(lcd_display, i2c_bus)
sleep(2) # Update interval
if __name__ == '__main__':
main()
pico:GP0
pico:GP1
pico:GND.1
pico:GP2
pico:GP3
pico:GP4
pico:GP5
pico:GND.2
pico:GP6
pico:GP7
pico:GP8
pico:GP9
pico:GND.3
pico:GP10
pico:GP11
pico:GP12
pico:GP13
pico:GND.4
pico:GP14
pico:GP15
pico:GP16
pico:GP17
pico:GND.5
pico:GP18
pico:GP19
pico:GP20
pico:GP21
pico:GND.6
pico:GP22
pico:RUN
pico:GP26
pico:GP27
pico:GND.7
pico:GP28
pico:ADC_VREF
pico:3V3
pico:3V3_EN
pico:GND.8
pico:VSYS
pico:VBUS
led1:A
led1:C
led2:A
led2:C
btn1:1.l
btn1:2.l
btn1:1.r
btn1:2.r
lcd1:GND
lcd1:VCC
lcd1:SDA
lcd1:SCL
dht1:VCC
dht1:SDA
dht1:NC
dht1:GND
bz1:1
bz1:2
relay1:VCC
relay1:GND
relay1:IN
relay1:NC
relay1:COM
relay1:NO
r1:1
r1:2
led3:A
led3:C