(3)ESP32 Python 制作一个办公室温度计

因为经常在办公室里面不知道实际室内温度是多少,所以用ESP32做了一个工具来进行温度&湿度的监测。在之前的文章当中,已经完成了ESP32的数据上云工作,如果要进行温度/湿度的检测。从原理上就是给ESP32连接对应的传感器,并把传感器的数据上报到阿里云物联网平台。
我们先来看看效果

这样的话,每天上班前在家里可以先看看办公室空调是否已经把公司的温度提升上去,如果没有提升上去。那说明可能空调有问题,今日的取暖只能靠抖了。
下面我们说说,这个实现怎么搞。首先在阿里云IOT平台上,对我们之前的产品添加2个功能分别为当前湿度和当前温度。

实现步骤如下:

  1. 根据所使用的硬件,进行board.json的配置。 因为我们的温度传感器使用的是sht3x, 使用I2C,在board.json的配置如下:
{
    "name": "haasedu",
    "version": "1.0.0",
    "io": { 
      "sht3x": {
        "type": "I2C",
        "port": 0,
        "addrWidth": 7,
        "freq": 400000,
        "mode": "master",
        "devAddr": 68
      } 
    },
    "debugLevel": "ERROR",
    "repl": "disable"
  }
  1. 实现代码
from driver import I2C   
import sht3x        
def report_iot_data(temperature, humidity ):
    upload_data = {'params': ujson.dumps({
        'CurrentHumidity': humidity, 'CurrentTemperature':temperature
    })
    }  
    device.postProps(upload_data)
    print('UPDATE IOT SUCCESS!!!')
    
def get_light_temp_humi():
    
    temperature = humitureDev.getTemperature()        
    humidity = humitureDev.getHumidity()    
    report_iot_data(temperature, humidity)
    return temperature, humidity
i2cObj = I2C() 
i2cObj.open("sht3x")   
humitureDev = sht3x.SHT3X(i2cObj)    
    
while True:
    data = get_light_temp_humi()    
    utime.sleep(3)

进行烧录就可以了。
获取温度湿润还需要使用Haas团队写的一个驱动,代码如下
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!")

将程序代码烧录到开发板后,设备会联网,并且每3秒上报一次数据。发布的数据, 我们可以在阿里云物联网平台上的设备的物模型数据中看到。


关于board.json的部分,需要根据自己采用的温度/湿度传感器,调整对应的GPIO的编号就行。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

炒陈饭老司机

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值