1. Haas python 轻应用 Esp32开发板 温度传感器使用

这篇博客是针对初学者的ESP32开发板和SHT3X温湿度传感器的使用教程。作者介绍了如何从零开始设置环境,包括连接硬件、编写Python代码、配置board.json文件以及部署和运行。虽然在实际运行中遇到了问题,但最终通过CMD成功执行了程序并获取了温湿度数据。
摘要由CSDN通过智能技术生成

Haas python 轻应用 Esp32开发板 温度传感器使用

注:因为我是不会python和开发板的等知识的(全是零基础),所以我就是纯粹的CV大法,这只是我个人初级入门的记录。

1.入门教程

haas 官网指导hellowrold教程
https://haas.iot.aliyun.com/haasapi/index.html#/Python/docs/zh-CN/startup/ESP32_startup

2.入门准备

1. Esp32 开发板(乐鑫 ESP32_DevKitC)

在这里插入图片描述

2.温湿度传感器(SHT3X温湿度传感器)

在这里插入图片描述

3.杜邦线4根

3. 接线

在这里插入图片描述
在这里插入图片描述

4. 用VScode的HaaS Studio新建一个hellowrold工程。

4.1 引入温湿度驱动

参考网站https://haas.iot.aliyun.com/solution/detail/hardware?versionId=800CD7F0F2F57FF800000002&dataId=800CD7F0F2F57FF8&s=

新建一个sht3x.py文件
内容如下:

在这里插入图片描述

"""
Copyright (C) 2015-2021 Alibaba Group Holding Limited

    MicroPython's driver for CHT8305

    Author: HaaS
    Date:   2021/09/14
"""

from micropython import const
import utime
from driver import I2C

'''
# sht3x commands definations
# read serial number:                            CMD_READ_SERIALNBR  0x3780
# read status register:                          CMD_READ_STATUS     0xF32D
# clear status register:                         CMD_CLEAR_STATUS    0x3041
# enabled heater:                                CMD_HEATER_ENABLE   0x306D
# disable heater:                                CMD_HEATER_DISABLE  0x3066
# soft reset:                                    CMD_SOFT_RESET      0x30A2
# accelerated response time:                     CMD_ART             0x2B32
# break, stop periodic data acquisition mode:    CMD_BREAK           0x3093
# measurement: polling, high repeatability:      CMD_MEAS_POLLING_H  0x2400
# measurement: polling, medium repeatability:    CMD_MEAS_POLLING_M  0x240B
# measurement: polling, low repeatability:       CMD_MEAS_POLLING_L  0x2416
'''

class SHT3X(object):

    # i2cDev should be an I2C object and it should be opened before __init__ is called
    def __init__(self, i2cDev):
        self._i2cDev = None
        if not isinstance(i2cDev, I2C):
            raise ValueError("parameter is not an I2C object")

        # make AHB21B's internal object points to _i2cDev
        self._i2cDev = i2cDev
        self.start()

    def start(self):
        # make sure AHB21B's internal object is valid before I2C operation
        if self._i2cDev is None:
            raise ValueError("invalid I2C object")

        # send clear status register command - 0x3041 - CMD_CLEAR_STATUS
        cmd = bytearray(2)
        cmd[0] = 0x30
        cmd[1] = 0x41
        self._i2cDev.write(cmd)

        # wait for 20ms
        utime.sleep_ms(20)

        return 0

    def getTempHumidity(self):
        if self._i2cDev is None:
            raise ValueError("invalid I2C object")

        tempHumidity = [-1, 2]

        # start measurement: polling, medium repeatability - 0x240B - CMD_MEAS_POLLING_M
        # if you want to adjust measure repeatability, you can send the following commands:
        # high repeatability: 0x2400 - CMD_MEAS_POLLING_H
        # low repeatability: 0x2416  - CMD_MEAS_POLLING_L
        cmd = bytearray(2)
        cmd[0] = 0x24
        cmd[1] = 0x0b
        self._i2cDev.write(cmd)

        # must wait for a little before the measurement finished
        utime.sleep_ms(20)

        dataBuffer = bytearray(6)
        # read the measurement result
        self._i2cDev.read(dataBuffer)

        # print(dataBuffer)
        # calculate real temperature and humidity according to SHT3X-DIS' data sheet
        temp = (dataBuffer[0]<<8) | dataBuffer[1]
        humi = (dataBuffer[3]<<8) | dataBuffer[4]

        tempHumidity[1] = humi * 0.0015259022
        tempHumidity[0] = -45.0 + (temp) * 175.0 / (0xFFFF - 1)

        return tempHumidity

    def getTemperature(self):
        data = self.getTempHumidity()
        return data[0]

    def getHumidity(self):
        data = self.getTempHumidity()
        return data[1]

    def stop(self):

        if self._i2cDev is None:
            raise ValueError("invalid I2C object")

        # stop periodic data acquisition mode
        cmd = bytearray(3)
        cmd[0] = 0x30
        cmd[1] = 0x93
        self._i2cDev.write(cmd)
        # wait for a little while
        utime.sleep_ms(20)

        self._i2cDev = None
        return 0

    def __del__(self):
        print('sht3x __del__')

if __name__ == "__main__":
    '''
    The below i2c configuration is needed in your board.json.
    "sht3x": {
        "type": "I2C",
        "port": 1,
        "addrWidth": 7,
        "freq": 400000,
        "mode": "master",
        "devAddr": 68
    },
    '''
    print("Testing sht3x ...")

    i2cDev = I2C()
    i2cDev.open("sht3x")

    sht3xDev = SHT3X(i2cDev)

    '''
    # future usage:
    i2cDev = I2C("sht3x")
    sht3xDev = sht3x.SHT3X(i2cDev)
    '''

    temperature = sht3xDev.getTemperature()
    print("The temperature is: %f" % temperature)

    humidity = sht3xDev.getHumidity()
    print("The humidity is: %f" % humidity)

    print("Test sht3x done!")


4.2 修改board.json
{
  "name": "board-name",
  "version": "1.0.0",
  "io": {
    "sht3x": {
      "type": "I2C",
      "port": 0,
      "addrWidth": 7,
      "freq": 400000,
      "mode": "master",
      "devAddr": 68
    }
  },
  "debugLevel": "ERROR",
  "repl": "disable"
}
4.3 写main.py
# Python代码
import utime                         # 延时API所在组件
from driver import I2C               # 驱动库
import sht3x                         # SHT3X-DIS温湿度传感器驱动库
i2cObj = I2C()
i2cObj.open("sht3x")                 # 按照board.json中名为"sht3x"的设备节点的配置参数(主设备I2C端口号,从设备地址,总线频率等)初始化I2C类型设备对象
print("sht3x inited!")
humitureDev = sht3x.SHT3X(i2cObj)    # 初始化SHT3X-DIS传感器
# 通过温湿度传感器读取温湿度信息
def get_temp_humi():
    temperature = humitureDev.getTemperature()         # 获取温度测量结果
    humidity = humitureDev.getHumidity()               # 获取相对湿度测量结果
    '''
    # 如果需要同时获取温湿度信息,可以呼叫getTempHumidity,实例代码如下:
    humniture = humitureDev.getTempHumidity()          # 获取温湿度传感器测量到的温湿度值
    temperature = humniture[0]                         # get_temp_humidity返回的字典中的第一个值为温度值
    humidity = humniture[1]                            # get_temp_humidity返回的字典中的第二个值为相对湿度值
    '''
    print("The temperature is: %.1f" % temperature)
    print("The humidity is: %d" % humidity)
    return temperature, humidity                        # 返回读取到的温度值和相对湿度值
if __name__ == '__main__':
    while True:
        data = get_temp_humi()                          # 读取温度信息和相对湿度信息
        utime.sleep(1)                                  # 每隔1秒钟进行一次温湿度信息测量和打印
    i2cObj.close()                                      # 关闭I2C设备对象
4.4 部署运行

在这里插入图片描述
在这里插入图片描述

(可能我的环境部署有问题,我的是运行报错的,不知道怎么解决,所以我是把命令复制到cmd窗口运行的)

cmd 部署运行成功
在这里插入图片描述

4.5 查看效果

可以直接用vscode下面菜单栏的串口查看(我这里有问题,查看不了),我用putty查看
在这里插入图片描述
在这里插入图片描述

下面是我真实的接线图
在这里插入图片描述

结束(大功告成)

第一次成功了,算是入门的一小步了。
加油,努力!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值