python - 如何使用 I²C 连接 Arduino Uno 和 Raspberry Pi

标签 python arduino raspberry-pi i2c

我正在尝试通过 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/

相关文章:

使用 Arduino 进行 Android 主机卡仿真

arduino - 如何将Arduino Uno用作FTDI程序员?

python - 为什么 Django 1.7 从 syncdb 迁移到 migrate?

python - 模块在 Python 中不可调用?

python - 如何在 numpy 数组中找到唯一的非 nan 值?

c - Arduino C 不进入循环?

Python I2C 通信 TTP229

Python错误email.mime没有属性 'MIMEMultipart'

java - 在 Raspberry Pi 上使用 Amazon Echo 控制 OpenHAB

python - 如何在nameko中使用service runner?