如何使用 Python 在 Raspberry Pi 上读取 I2C 压力传感器

How to read from an I2C pressure sensor on Raspberry Pi using Python

对于我当前的项目,我已将 MEAS M32JM 压力和温度传感器连接到我的 Pi,但我一直无法使用其 I2C 协议读取传感器值。

这是传感器的数据表: https://eu.mouser.com/datasheet/2/418/8/ENG_DS_M3200_A19-1958281.pdf

注意:查看数据表末尾的 C 示例代码

数据表提到:

The I2C address consists of a 7-digit binary value. The factory setting for the I2C slave address is 0x28. The address is always followed by a write bit (0) or read bit (1). The default hexadecimal I2C header for read access to the sensor is therefore 0x51.

这是我试过的:

import smbus
import time

bus = smbus.SMBus(1)
address = 0x28
read_header = 0x51

bus.write_byte_data(address, read_header, 0x01)  # Start reading: 0 = WRITE, 1 = READ

time.sleep(0.7)

for i in range(8):
    print(bus.read_byte_data(address, i))

然而,所有打印件 return 0.

datasheet 还提到在发送读取位后,我们必须等待 acknowledge 位,但我将如何接收和处理该位?

之前从未使用过 I2C 或按位运算,因此非常感谢任何有关如何从该传感器读取数据的帮助!

设法使用 pigpio 而不是 smbus 来解决它。

我在 Pi 上安装它使用:

apt install pigpio
apt-get install python-pigpio python3-pigpio

然后我使用下面的Python脚本来读取传感器数据:

import pigpio

SENSOR_ADDRESS = 0x28  # 7 bit address 0101000-, check datasheet or run `sudo i2cdetect -y 1`
BUS = 1

pi = pigpio.pi()

handle = pi.i2c_open(BUS, SENSOR_ADDRESS)

# Attempt to write to the sensor, catch exceptions
try:
  pi.i2c_write_quick(handle, 1)  # Send READ_MR command to start measurement and DSP calculation cycle
except:
  print("Error writing to the sensor, perhaps none is connected to bus %s" % bus, file=sys.stderr)
  pi.stop()
  return None

time.sleep(2 / 1000)  # Give the sensor some time

count, data = pi.i2c_read_device(handle, 4)  # Send READ_DF4 command, to fetch 2 pressure bytes & 2 temperature bytes

pi.i2c_close(handle)
pi.stop()

print("count = ", count)
print("data = ", data)

Click here to see the full script.