from machine import Pin
import time
import random #生成随机数(做 “模拟波动”)
# Wokwi 更稳的导入写法
from dht import DHT22 #专门驱动 DHT22 传感器
# 关键:Wokwi 常用 GPIO15(D15)
sensor = DHT22(Pin(15))
#定义量程(DHT22 真实范围)
TEMP_MIN = -40
TEMP_MAX = 80
HUMI_MIN = 0
HUMI_MAX = 100
if __name__ == "__main__":
time.sleep(1)
while True:
try:
#读取传感器原始数据
sensor.measure()
base_temp = sensor.temperature()#真实温度传感器读数
base_humi = sensor.humidity()
# 随机扰动,给温度加随机小波动
temp_noise = random.uniform(-0.5, 0.5)#温度测量精度在0.5°
noisy_temp = base_temp + temp_noise
noisy_temp = max(TEMP_MIN, min(noisy_temp, TEMP_MAX))#防止温度跑出 -40℃ ~ 80℃ 的传感器量程
#给湿度加随机波动
humi_noise = random.uniform(-0.02, 0.02)#湿度测量精度在2%RH,取0.02跳度更自然
noisy_humi = base_humi + humi_noise
noisy_humi = max(HUMI_MIN, min(noisy_humi, HUMI_MAX))#防止湿度跑出 0–100%RH传感器量程
print("原始温湿度:" )
print("temp=%.2f℃ humi=%.2f%%RH" % (base_temp, base_humi))
print("调整后温湿度:" )
print("temp=%.2f℃ humi=%.2f%%RH" % (noisy_temp, noisy_humi))
print("----------------------------------" )
except Exception as e:
print("DHT22传感器检测失败!错误:", e)
time.sleep(2)