簡體   English   中英

I2C 傳感器讀取 Raspberry Pi 和 Arduino 的差異

[英]Difference I2C Sensor Reading Raspberry Pi and Arduino

我正在使用 Sensirion SFM3300 流量傳感器,可以使用以下代碼 (I2C) 使用 Arduino 讀取正確值:

#include <Wire.h>

void setup() {
  // put your setup code here, to run once:
  Wire.begin();
  Serial.begin(115200);
  Wire.beginTransmission(byte(0x40));
  Wire.write(byte(0x10));
  Wire.write(byte(0x00));
  Wire.endTransmission();
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(100);
  Wire.requestFrom(0x40,2);
  uint16_t a = Wire.read();
  uint8_t  b = Wire.read();
  a = (a<<8) | b;
  float flow = ((float)a - 32768) / 120;
  Serial.println(flow);
}

但是使用 Raspberry Pi 我編寫了幾乎相同的代碼,希望它也能工作。 這是代碼:

from smbus2 import SMBus
import time
import numpy as np

address=0x40
bus = SMBus(1)

def write(value):
    bus.write_byte(address,value)

write(0x10)
write(0x00)

while True:
    time.sleep(0.1)
    a = np.uint16(bus.read_byte(0x40))
    b = np.uint8(bus.read_byte(0x40))
    a = (a<<8) | b
    flow = (float(a)-32768)/120
    print(flow)

代碼看起來真的一樣,但我只得到 -273,06666666666 作為返回值。 有人知道 Raspberry Pi 和 Arduino I2C 之間的區別在哪里,可以幫助我在 Pi 上獲得正確的值嗎?

您可以使用read_i2c_block_data(addr, offset, numOfBytes)方法從 i2c 中獲取超過 1 個字節的數據。 返回數據是一個字節列表。 所以很容易轉換成整數。

根據數據表和 Arduino 草圖編輯

這是應與 Arduino 示例匹配的 Python 完整代碼:

from SMBus2 import SMBus
import time

offset = 32768
scale = 120

addr = 0x40
cmd = [0x10, 0x00]

with SMBus(1) as bus:
    bus.write_i2c_block_data(addr, 0, cmd)
    time.sleep(0.1)
    block = bus.read_i2c_block_data(addr, 0, 3)
reading = block[0] * 256 + block[1]
crc = block[2]    # should do some crc check for error
flow = (reading - offset)/scale
print(flow)

我不認為你在 python 中的讀取過程是正確的。 從端口 40 讀取兩次與從端口 40 讀取兩個字節不同。

我建議使用 read_byte_data(0x40, 0, 2) 並使用struct.unpack(">H")

我找到了一個可行的解決方案。 如果 I2C 專家能告訴我為什么下面的代碼可以工作而不是上面的 python 代碼,那就太好了。

from fcntl import ioctl
from struct import unpack
from smbus import SMBus

address = 0x40

SMBus(1).write_byte_data(address,16,0)
i2c = open("/dev/i2c-1", "rb", buffering=0)
ioctl(i2c,0x0703,address)
i2c.read(3)

d0,d1,c = unpack('BBB', i2c.read(3))
d = d0 << 8 | d1
a = (float(d)-32768.)/120
print(a)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM