本帖最后由 sacq 于 2018-8-5 20:12 编辑
HTU21D : 采用I2C接口的温湿度传感器,是厂家在本论坛活动时申请得到的,封装极小,个人焊接、固定难度很大。
接法:4个引脚, 供电3.3,地,DATA,SCK
找了几段驱动代码,用了这个合适(HTU21D.PY):
import pyb
class HTU21D:
i2c = None
# HTU21D Address
address = 0x40
# Commands
TRIGGER_TEMP_MEASURE_HOLD = 0xE3
TRIGGER_HUMD_MEASURE_HOLD = 0xE5
READ_USER_REG = 0xE7
# Constructor
def __init__(self):
self.i2c = pyb.I2C(1, pyb.I2C.MASTER)
def readUserRegister(self):
#Read the user register byte
return self.i2c.mem_read(1,self.address,self.READ_USER_REG)
def readTemperatureData(self):
#Read 3 temperature bytes from the sensor
# value[0], value[1]: Raw temperature data
# value[2]: CRC
value = self.i2c.mem_read(3,self.address,self.TRIGGER_TEMP_MEASURE_HOLD)
if not self.crc8check(value):
return -255
rawTempData = ( value[0] << 8 ) + value[1]
rawTempData = rawTempData & 0xFFFC; # Clear the status bits
# Calculate the actual temperature
actualTemp = -46.85 + (175.72 * rawTempData / 65536)
return actualTemp
def readHumidityData(self):
#Read 3 humidity bytes from the sensor
# value[0], value[1]: Raw relative humidity data
# value[2]: CRC
value = self.i2c.mem_read(3,self.address,self.TRIGGER_HUMD_MEASURE_HOLD)
if not self.crc8check(value):
return -255
rawRHData = ( value[0] << 8 ) + value[1]
rawRHData = rawRHData & 0xFFFC; # Clear the status bits
# Calculate the actual RH
actualRH = -6 + (125.0 * rawRHData / 65536)
return actualRH
def crc8check(self, value):
#Calulate the CRC8 for the data received
# from
https://github.com/sparkfun/HTU21D_Breakout
remainder = ( ( value[0] << 8 ) + value[1] ) << 8
remainder |= value[2]
# POLYNOMIAL = 0x0131 = x^8 + x^5 + x^4 + 1
# divsor = 0x988000 is polynomial shifted to farthest left of three bytes
divsor = 0x988000
for i in range(0, 16):
if( remainder & 1 << (23 - i) ):
remainder ^= divsor
divsor = divsor >> 1
if remainder == 0:
return True
else:
return False
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
测试代码:
import time
import HTU21D
htu=HTU21D.HTU21D()
while True:
time.sleep(0.5)
print("T:%2.2f, H:%2.2f"%(htu.readTemperatureData(),htu.readHumidityData())) # readTemperatureData(self)
效果:
HTU21D.zip
(1.06 KB, 下载次数: 4)
此内容由EEWORLD论坛网友sacq原创,如需转载或用于商业用途需征得作者同意并注明出处