from machine import Pin
import time
import dht
import random # 导入随机数模块
# 定义DHT11控制对象
dht11 = dht.DHT11(Pin(27))
# 程序入口
if __name__ == "__main__":
time.sleep(1) # 首次启动间隔1S让传感器稳定
while True:
dht11.measure() # 调用DHT类库中测量数据的函数
temp = dht11.temperature()
humi = dht11.humidity()
if temp is None:
print("DHT11传感器检测失败!")
else:
# 给温度和湿度加上符合传感器精度的微小随机波动
# 温度波动:±2℃
temp_with_rand = temp + random.uniform(-2, 2)
# 湿度波动:±5%RH
humi_with_rand = humi + random.uniform(-5, 5)
# 格式化输出,保留1位小数
print("temp=%.1f°C humi=%.1fRH" % (temp_with_rand, humi_with_rand))
time.sleep(2) # 间隔2秒读取一次