因为经常在办公室里面不知道实际室内温度是多少,所以用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. gulp图片压缩
  2. POJ 3009
  3. C# 对象的序列化与反序列化 (DataContractJsonSerializer)
  4. linux kernel 0.11 bootsect
  5. (剑指Offer)面试题24:二叉搜索树的后序遍历序列
  6. POJ 2993Emag eht htiw Em Pleh
  7. JAVA并发实现二(线程中止)
  8. 新手向--git版本控制器
  9. fast-fail事件的产生及其解决办法
  10. Java Web请求和响应机制
  11. python学习-判断是否是IP地址
  12. 【用jersey构建REST服务】系列文章
  13. js中怎么写自执行函数
  14. python第二十四课——set中的函数
  15. 【AHOI2012】信号塔
  16. $(window).load与$(document).ready的区别
  17. linq to sql: 在Entityfamework Core中使用多个DbContext
  18. vim-程序员的利器
  19. javascript基础-js对象
  20. 如何提升集群资源利用率? 阿里容器调度系统Sigma 深入解析

热门文章

  1. SPQuery ViewAttributes Sharepoint列表查询范围
  2. JAVA判断某个元素是否在某个数组中
  3. 【LeetCode】36. Valid Sudoku 解题报告(Python)
  4. Linux中架构中的备份服务器搭建(rsync)
  5. iGPT and ViT
  6. element ui el-tree回显问题及提交问题(当后台返回的el-tree相关数组的时候,子菜单未全部选中,但是只要父级菜单的id在数组中,那么他的子菜单为全部选中状态)
  7. Java EE数据持久化框架 • 【第3章 MyBatis高级映射】
  8. 【MySQL作业】连接查询综合应用——美和易思连接查询综合应用习题
  9. 编写Java程序,实现多线程操作同一个实例变量的操作会引发多线程并发的安全问题。
  10. playwright--自动化(二):过滑块验证码 验证码缺口识别