# LCD1602: SDA=17, SCL=16
# Buzzer: 12
# LED: 14
from machine import Pin, SoftI2C, PWM
from lcd_i2c import I2cLcd
import dht
import time
# 构造DHT22控制对象
dht22 = dht.DHT22(Pin(13))
# 首次启动间隔1s让传感器稳定
time.sleep(1)
# 定义I2C控制对象
i2c = SoftI2C(sda=Pin(17), scl=Pin(16), freq=100000)
# 获取I2C设备地址
address = i2c.scan()[0]
# 定义LCD对象
i2c_lcd = I2cLcd(i2c, address, 2, 16)
# 定义LED引脚
led = Pin(14, Pin.OUT)
# 定义无源蜂鸣器PWM控制对象
buzzer = PWM(Pin(12), Pin.OUT)
# 初始化蜂鸣器占空比为0,否则会有噪音
buzzer.duty(0)
# 获取传感器温度
def getTemp():
dht22.measure()
temp = dht22.temperature()
time.sleep(2)
return temp
# 获取传感器湿度
def getHumi():
dht22.measure()
humi = dht22.humidity()
time.sleep(2)
return humi
# LCD1602显示温湿度函数
def display(temp, humi):
i2c_lcd.clear()
i2c_lcd.putstr(f"temp: {temp}C humi: {humi}%")
# LED发光函数
def glowing(temp, humi):
if temp > 40 or humi < 60:
led.value(1)
else:
led.value(0)
# 蜂鸣器报警函数
def warning(temp, humi):
if temp > 40 or humi < 60:
# 占空比控制蜂鸣器音量
buzzer.duty(1023)
# 频率控制蜂鸣器音调
buzzer.freq(5000)
time.sleep(1)
else:
buzzer.duty(0)
time.sleep_ms(10)
if __name__ == "__main__":
while True:
temp = getTemp()
humi = getHumi()
print(f"temp={temp}C humi={humi}%")
display(temp, humi)
glowing(temp, humi)
warning(temp, humi)