繁体   English   中英

如何使用 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 示例代码

数据表提到:

I2C 地址由一个 7 位二进制值组成。 I2C 从地址的出厂设置为 0x28。 地址后面始终跟有写入位 (0) 或读取位 (1)。 因此,用于读取传感器的默认十六进制 I2C header 为 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))

但是,所有打印件都返回0

数据表还提到发送读取位后,我们必须等待确认位,但我将如何接收和处理该位?

以前从未使用过 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)

单击此处查看完整脚本

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM