【问题标题】:How do I connect an Arduino Uno with Raspberry Pi using I²C如何使用 I²C 将 Arduino Uno 与 Raspberry Pi 连接
【发布时间】:2012-12-14 17:43:28
【问题描述】:

我正在尝试使用 I²C 通过I²C 接口将数据从Arduino Uno 发送到Raspberry Pi。这是我使用的代码。

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

在树莓派中:

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)

我收到以下错误。

回溯(最近一次通话最后一次):

中的文件“/home/pi/i2ctest.py”,第 8 行 watt = bus.read_byte_data(地址,1)
IOError: [Errno 5] 输入/输出错误

我该如何解决这个问题?另外,除了 SMBus 库之外,在 Raspberry Pi 中使用 I²C 是否还有其他选择?

【问题讨论】:

    标签: python arduino raspberry-pi i2c


    【解决方案1】:

    如果您的 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 程序。

    【讨论】:

    • 我运行了修订版 1,并使用 i2cdetect 0 -y 对其进行了测试,它显示了正确的地址。我发现了它的问题(这是 arduino 正在等待来自 rpi 的信号,但它从来没有出现过。我已经删除了那条线)但现在我遇到了另一个问题,rpi 的 i2c 输入始终为 0,无论我是什么从 arduino 传输
    • 在 Arduino 上,如果您将值乘以 5 / 1023,我相信这将始终为 0。尝试 5.0 / 1023。
    • @user17151:你用的是上拉电阻吗? I2C 是“开漏”线,不能上拉信号,因此需要上拉电阻才能达到 +V。 (如果您还没有使用这些,请参阅任何 I2C 教程。)
    • 另外,请记住 Rpi 上的 i2c 兼容 3.3v,而 arduino 上的 i2c 是 TTL 电平 (5V)。所以你需要一个转换电路来改变电平。 (类似这样的东西:playground.arduino.cc/uploads/Main/i2c-level-shift-mosfet.png)并且根据 tom10 指出的,您需要拉起线路。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 2021-05-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多