小钢炮开发板带有HTS221温湿度传感器,这个温湿度传感器和STH22/si7002不同,不能直接读取温度和湿度,需要通过插值进行计算。
下面是我写的HTS221驱动,可以通过函数直接读取温度和湿度常数。
# HTS221 Humidity and temperature micropython drive# Author: shaoziyang# 2016.4import pybfrom pyb import I2CHTS_I2C_ADDR = 0x5Fclass HTS221(object): def __init__(self, i2cn): self.i2c = I2C(i2cn, I2C.MASTER, baudrate = 100000) # HTS221 Temp Calibration registers self.T0_OUT = self.get2Reg(0x3C) self.T1_OUT = self.get2Reg(0x3E) if self.T0_OUT>=0x8000 : self.T0_OUT -= 65536 if self.T1_OUT>=0x8000 : self.T1_OUT -= 65536 t1 = self.getReg(0x35) self.T0_degC = (self.getReg(0x32) + (t1%4)*256)/8 self.T1_degC = (self.getReg(0x33)+ ((t1%16)/4)*256)/8 # HTS221 Humi Calibration registers self.H0_OUT = self.get2Reg(0x36) self.H1_OUT = self.get2Reg(0x3A) self.H0_rH = self.getReg(0x30)/2 self.H1_rH = self.getReg(0x31)/2 # set av conf: T=4 H=8 self.setReg(0x81, 0x10) # set CTRL_REG1: PD=1 BDU=1 ODR=1 self.setReg(0x85, 0x20) def setReg(self, dat, reg): buf = bytearray(2) buf[0] = reg buf[1] = dat i2c = self.i2c i2c.send(buf, HTS_I2C_ADDR) def getReg(self, reg): i2c = self.i2c i2c.send(reg, HTS_I2C_ADDR) t = i2c.recv(1, HTS_I2C_ADDR) return t[0] def get2Reg(self, reg): a = self.getReg(reg) b = self.getReg(reg + 1) return a + b * 256 def av(self, av=''): i2c = self.i2c if av != '': #buf = bytearray(2) #buf[0] = 0x10; #buf[1] = av; #i2c.send(buf, HTS_I2C_ADDR) self.setReg(av, 0x10) else: #i2c.send(0x10, HTS_I2C_ADDR) #t = i2c.recv(1, HTS_I2C_ADDR) #return t[0] return self.getReg(0x10) def T0_OUT(self): return self.T0_OUT def T1_OUT(self): return self.T1_OUT def T0_degC(self): return self.T0_degC def T1_degC(self): return self.T1_degC # calculate Temperature def getTemp(self): t = self.get2Reg(0x2A) return self.T0_degC + (self.T1_degC - self.T0_degC) * (t - self.T0_OUT) / (self.T1_OUT - self.T0_OUT) def H0_OUT(self): return self.H0_OUT def H1_OUT(self): return self.H1_OUT def H0_rH(self): return self.H0_rH def H1_rH(self): return self.H1_rH # calculate Humidity def getHumi(self): t = self.get2Reg(0x28) return self.H0_rH + (self.H1_rH - self.H0_rH) * (t - self.H0_OUT) / (self.H1_OUT - self.H0_OUT)
先将hts221.py复制到小钢炮的PYFLASH磁盘,然后就可以使用函数读取温度湿度
PYB: sync filesystemsPYB: soft rebootMicroPython v1.7 on 2016-04-17; CANNON with STM32F401xEType "help()" for more information.>>> from hts221 import HTS221>>> hts=HTS221(1)>>> hts.getTemp()22.95221>>> hts.getHumi()82.62943>>>