一环境:
Thonny 4.1.3
win10
Python 3.10.11
硬件:
ESP-WROOM-32开发板
SHT31-DIS-B2.5kS传感器
示例程序
from machine import Pin, I2C
import time
i2c = I2C(0)
i2c = I2C(1, scl=Pin(18), sda=Pin(19), freq=400000) # 数构造并返回一个新的 I2C 对象
i2c.scan() # scan for devices 0x08 和 0x77 之间的所有 I2C 地址
def read_SH31():
SHT31_I2CADDR = 0x44 # 传感器地址
CMD_MEASURE = bytearray([0x2C, 0x06]) # Measurement Commands for Single Shot Data Acquisition Mode 详见数据手册
i2c.writeto(SHT31_I2CADDR, CMD_MEASURE)
time.sleep(0.01) #等待设备响应
data = i2c.readfrom(SHT31_I2CADDR, 6) #读取传感器数据
temp = -45 + 175 * ((data[0] << 8 | data[1]) / 65535)
temp = round(temp, 2)
humidity = 100 * ((data[3] << 8 | data[4]) / 65535)
humidity =round(humidity, 2)
return temp, humidity
def main():
while True:
temp, humidity = read_SH31()
print('温度: '+str(temp)+', 湿度: '+str(humidity))
time.sleep(1)
上面程序是用硬件I2C总线,也可以用软件I2C总线
from machine import Pin, SoftI2C
i2c = SoftI2C(scl=Pin(21), sda=Pin(22), freq=100000)