如何使用I²C将Arduino Uno与Raspberry Pi连接

2024-09-30 14:36:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过I²C接口使用I²C将数据从Arduino Uno发送到{a3}。这就是我使用的代码。在

在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);
}

在覆盆子派里:

^{pr2}$

我收到了以下错误。在

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吗?在


Tags: serialbytearduinointdelaybeginwirevoid
1条回答
网友
1楼 · 发布于 2024-09-30 14:36:19

如果您有一个带有版本2.0的Raspberry Pi,则需要使用I²C总线1,而不是总线0,因此需要更改所使用的总线编号。在这种情况下,线路

bus = smbus.SMBus(0) 

会变成

^{pr2}$

您可以使用i2ctools包中的i2cdetect程序检查设备是否存在于总线上。试试看

i2cdetect 0 -y 

在0路公交车上找阿杜伊诺。跑

i2cdetect 1 -y 

在1路公交车上找。当然,必须运行Arduino程序才能使其工作。这也将确认Arduino在预期地址。在

您还需要确保您拥有使用I²C的适当权限,因此从i2c组成员的帐户运行Python程序。在

相关问题 更多 >