我正在尝试通过 I²C 发送数据来自 Arduino Uno 的界面到 Raspberry Pi使用 I²C。这是我使用的代码。
在 Arduino 中:
#include <Wire.h>
unsigned int watt;
unsigned int watt1;
byte watt2;
byte watt3;
void setup()
{
Wire.begin(30);
Wire.onRequest(requestEvent);
Serial.begin(9600);
}
void loop() {
delay(100);
int sensorValue = analogRead(A0);
int sensorValue1 = analogRead(A1);
watt = sensorValue * (5 / 1023) * 2857;
watt1 = sensorValue1 * (5 / 1023) * 2857;
watt2 = map(watt, 0, 4294967295, 0, 255);
watt3 = map(watt1, 0, 4294967295, 0, 255);
Serial.println(watt2);
Serial.println(watt3);
}
void requestEvent()
{
Wire.write(watt2);
delay(30);
Wire.write(watt3);
}
在 Raspberry Pi 中:
import smbus
import time
bus = smbus.SMBus(0)
address = 0x1e
while (1):
watt=bus.read_byte_data(address,1)
watt2=bus.read_byte_data(address,2)
我收到以下错误。
Traceback (most recent call last):
File "/home/pi/i2ctest.py" , line 8, in <module>
watt = bus.read_byte_data(address,1)
IOError: [Errno 5] Input/Output error
我该如何解决这个问题?此外,除了 SMBus 库之外,在 Raspberry Pi 中使用 I²C 是否有任何替代方案?
最佳答案
如果您的 Raspberry Pi 带有修订版 2.0 板,您需要使用 I²C 总线 1,而不是总线 0,因此您需要更改使用的总线编号。在这种情况下,行
bus = smbus.SMBus(0)
会变成
bus = smbus.SMBus(1)
您可以使用 i2ctools 包中的 i2cdetect 程序检查总线上是否存在设备。尝试
i2cdetect 0 -y
在总线 0 上寻找 Arduino。运行
i2cdetect 1 -y
在总线 1 上寻找它。当然,Arduino 程序必须正在运行才能工作。这也将确认 Arduino 出现在预期地址。
您还需要确保您拥有使用 I²C 的适当权限,因此请从属于 i2c
组成员的帐户运行您的 Python 程序。
关于python - 如何使用 I²C 连接 Arduino Uno 和 Raspberry Pi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13883715/