我正在尝试使用来自Adafruit的产品2635的Texas Instruments HDC1008来读取温度和湿度。我使用smbus模块在rasberry pi 2上。根据TI的PDF,在获取读数时,数字将以您放在一起的两个字节发送。我发现this code执行了我正在尝试用micropython做的事情,他们有一个recv
函数,它似乎只是将它们发送回一个包含两个字节的列表。 SMBus模块似乎没有任何等同于我正在尝试做的事情。这是我的一些代码。
class HDC1008:
I2C_BUS = 1
#Registers
REG_TEMP = 0
REG_HUMID = 1
REG_CONFIG = 2
#Configuration bits
CFG_RST = 1<<15
CFG_MODE_SINGLE = 0 << 12
CFG_MODE_BOTH = 1 << 12
ADDRESS = 0x40
def __init__(self, bus_num=I2C_BUS):
self.bus=smbus.SMBus(bus_num)
def readTemperature(self):
#configure the HDC1008 for one reading
config = 0
config |= self.CFG_MODE_SINGLE
self.bus.write_byte_data(self.ADDRESS, self.REG_CONFIG, config)
#tell the thing to take a reading
self.bus.write_byte(self.ADDRESS, self.REG_TEMP)
time.sleep(0.015)
#get the reading back from the thing
raw = self.bus.read_byte(self.ADDRESS)
raw = (raw<<8) + self.bus.read_byte(self.ADDRESS)
#use TI's formula to turn it into people numbers
temperature = (raw/65536.0)*165.0 - 40
#convert temp to f
temperature = temperature * (9.0/5.0) + 32
return temperature
当我从bus.read_byte获取raw
的值时,我能够得到温度位的前半部分,但第二次读数只是零,大概是因为第一次交易结束了。如何在一个事务中获得两个字节?
答案 0 :(得分:1)
tnx分享这段代码很多。我很高兴能用Python工作。
我不完全理解这个问题,我可以用我们的代码读取温度和湿度(我能找到并且有效的唯一Python代码)
我做了一点改变(让它成为一个班级):
GROUP BY Name
在该计划中:
import smbus
class HDC:
#Registers
REG_TEMP = 0
REG_HUMID = 1
REG_CONFIG = 2
I2C_BUS = 2 #2 for PCDuino, 1 for PI
#Configuration bits
CFG_RST = 1<<15
CFG_MODE_SINGLE = 0 << 12
CFG_MODE_BOTH = 1 << 12
ADDRESS = 0x40
def __init__(self, bus_num=I2C_BUS):
self.bus=smbus.SMBus(bus_num)
def readTemperature(self):
#configure the HDC1008 for one reading
config = 0
config |= self.CFG_MODE_SINGLE
self.bus.write_byte_data(self.ADDRESS, self.REG_CONFIG, config)
#tell the thing to take a reading
self.bus.write_byte(self.ADDRESS, self.REG_TEMP)
time.sleep(0.015)
#get the reading back from the thing
raw = self.bus.read_byte(self.ADDRESS)
raw = (raw<<8) + self.bus.read_byte(self.ADDRESS)
#use TI's formula to turn it into people numbers
temperature = (raw/65536.0)* 165 - 40
#convert temp to farenheid
#temperature = temperature * (9.0/5.0) + 32
return temperature
def readHum(self):
#configure the HDC1008 for one reading
config = 0
config |= self.CFG_MODE_SINGLE
self.bus.write_byte_data(self.ADDRESS, self.REG_CONFIG, config)
#tell the thing to take a reading
self.bus.write_byte(self.ADDRESS, self.REG_HUMID)
time.sleep(0.015)
#get the reading back from the thing
raw = self.bus.read_byte(self.ADDRESS)
raw = (raw<<8) + self.bus.read_byte(self.ADDRESS)
hum=(raw/(2.0**16))*100
return hum