from machine import I2C, Pin
import time
from i2c_lcd1602 import I2C_LCD1602 # 需部署专用驱动库
import dht
import machine
import time
# Set up the DHT22 sensor on GPIO pin 20
sensor = dht.DHT22(machine.Pin(20))
# 初始化I2C总线(推荐参数)
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400_000)
# 扫描设备地址(关键步骤)
print("检测到I2C设备:", [hex(addr) for addr in i2c.scan()]) # 输出应为0x27/0x3F等[6](@ref)
# 创建LCD对象(参数:地址、列数、行数)
lcd = I2C_LCD1602(i2c, 0x27)
# 初始化开关
push_switch=Pin(2, Pin.IN)
slide_switch= Pin(28, Pin.IN)
led=Pin(26,Pin.OUT)
while True:
try:
# Measure temperature and humidity
sensor.measure()
# Get temperature and humidity values
temperature = sensor.temperature() # In Celsius
humidity = sensor.humidity() # In percentage
# Print the temperature and humidity
print('Temperature: {}°C'.format(temperature))
print('Humidity: {}%'.format(humidity))
if(slide_switch.value()):
# 初始化显示
lcd.clear()
lcd.backlight(True) # 开启背光
led.on()
lcd.puts('Tem: {}°C'.format(temperature), 0, 0) # 第一行显示
lcd.puts('Hum: {}%'.format(humidity), 0, 1) # 第二行显示
else:
lcd.clear()
lcd.backlight(False)
led.off()
except OSError as e:
print('Failed to read sensor data:', e)
time.sleep(1) # Wait 2 seconds before next reading