import machine
import time
# AHT20 I2C地址
AHT20_I2C_ADDR = 0x38
# 初始化I2C
i2c = machine.I2C(0, scl=machine.Pin(18), sda=machine.Pin(19), freq=50000)#Pin要根据实际接线情况进行调整
def aht20_init():
# 发送初始化命令(校准)
i2c.writeto(AHT20_I2C_ADDR, bytes([0xBE, 0x08, 0x00]))
time.sleep_ms(10) # 等待初始化完成
def aht20_read():
# 发送触发测量命令
i2c.writeto(AHT20_I2C_ADDR, bytes([0xAC, 0x33, 0x00]))
time.sleep_ms(80) # 等待测量完成(根据数据手册建议)
# 等待传感器就绪
for _ in range(100):
status = i2c.readfrom(AHT20_I2C_ADDR, 1)[0]
if not (status & 0x80): # 检查忙标志位
break
time.sleep_ms(5)
else:
raise Exception("AHT20 响应超时")
# 读取6字节数据
data = i2c.readfrom(AHT20_I2C_ADDR, 6)
# 解析湿度数据(20位)
raw_humidity = ((data[1] << 16) | (data[2] << 8) | data[3]) >> 4
humidity = (raw_humidity / (2**20)) * 100
# 解析温度数据(20位)
raw_temp = ((data[3] & 0x0F) << 16) | (data[4] << 8) | data[5]
temperature = (raw_temp / (2**20)) * 200 - 50
return round(temperature, 1), round(humidity, 1)
# 初始化传感器
try:
aht20_init()
except:
print("初始化失败,请检查连接")
# 主循环
while True:
try:
temp, humi = aht20_read()
print(f"温度: {temp}℃, 湿度: {humi}%")
except Exception as e:
print("读取失败:", e)
time.sleep(2)
11-13
907

01-20