使用i2c,python和raspberry pi读取14位数据

时间:2015-11-22 21:41:17

标签: python raspberry-pi i2c

我正在尝试使用python& amp;读取覆盆子pi上的this barometric pressure sensor数据。 I2C / SMBus的。

传感器的数据表(第10页)表示它将输出0-16383(2 ** 14)范围内的数字值。到目前为止,似乎我必须读取整个字节,所以我不知道如何获得14位值。 (我有一个数据表的链接,但SO说我需要更多声誉才能添加更多链接到帖子。)

此示例使用Adafruit's I2C python library,它基本上是SMBus的包装。

import Adafruit_I2C
import time

# sensor returns a 14-bit reading 
max_output = 2**14 
# per data sheet, max_output == 1.6 bar
max_bar = 1.6

# i2c address specified in data sheet
sensor = Adafruit_I2C.Adafruit_I2C(0x78)

while True:
  reading = sensor.readU16(0, little_endian=False)

  # reading is sometimes, but not always, greater than 2**14
  # this adjustment feels pretty hacky/wrong
  while reading > max_output:
    reading = reading >> 1

  bar = reading / float(max_output) * max_bar
  print bar
  time.sleep(1)

我将这些读数与手持GPS的输出进行比较,其中包括气压计。我有时得到的读数有点接近(当GPS读数为1001毫巴时为1030毫巴),但传感器则会急剧下降(低至930毫巴)以获得一些读数。我怀疑这是由于我如何阅读数据,但没有真正的证据支持这一点。

此时,我不确定下一步该尝试什么。

我已经猜到了一些事情,但我会感激一些更明智的帮助:

  • 如何只读取传感器正在输出的14位?
  • 返回的值是什么字节序?假设big-endian产生的值似乎更健全,但我可能会在这里混淆多个问题。
  • 如何判断要读取的寄存器?这在任何地方的数据表中都没有提到。我猜测寄存器0可能是唯一的一个。

1 个答案:

答案 0 :(得分:1)

您应该屏蔽传感器的输出,而不是移动它。例如.write应该这样做。

前两位是状态位,因此如果设置它们,有时它们可​​能意味着:正常模式或陈旧数据指示符。