我正在使用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上获得正确的值吗?
我认为您在python中的读取过程不正确。从端口40读取两次不同于从端口40读取两个字节。
我建议使用read_byte_data(0x40,0,2)并用struct.unpack(">H")
处理。
您可以使用read_i2c_block_data(addr, offset, numOfBytes)
方法从i2c获取1个字节以上的数据。返回数据是字节列表。因此,将其转换为整数非常容易。
from SMBus2 import SMBus
with SMBus(1) as bus:
block = bus.read_i2c_block_data(0x40, 0, 2)
value = block[0] * 256 + block[1]
flow = (value - 32768)/120
print(flow)