ESP32读取SHT31温湿度(Micorpython)

一环境:

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)

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值