簡體   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