出现IOError:[Errno 121]尝试从Arduino通过I2C获取数据时,python(树莓)上的smbus出现远程I / O错误

时间:2018-10-10 08:30:01

标签: python arduino raspberry-pi i2c smbus

我遇到了问题,即pyhton在启动脚本(通过I2C向Arduino请求数据)时,有时把我扔在我的raspberry pi 3上。

电气连接是完美的,所以这不是问题。 此外,使用i2cget -y 1 0x04

时也没有任何错误。

只有python脚本很烂,我不知道为什么。

这是我的Arduino代码:

我注册了一个onReceive和一个onRequestEvent。 onReceive回调将定义应将哪种数据发送回树莓派。 onRequest回调会做出响应。

    #include <CommonFunction.h>
#include <Wire.h>

#define I2C_ADDRESS 0x4

commonFunc GetCountsEverySecond;
int g_iOnRequestActionCode = 0;
unsigned long g_lSecondsSinceStart = 0;

void setup() 
{
    Wire.begin(I2C_ADDRESS);
    Wire.onRequest(sendDataOverI2CGateway);
    Wire.onReceive(defineOnRequestAction);
}


void loop() 
{
    tickSeconds();
}

void tickSeconds()
{
    if (GetCountsEverySecond.TimeTriggerAt(1000))
    {
        g_lSecondsSinceStart++;
    }
}

void sendOperationTimeDataOverI2C()
{
    unsigned long longInt = g_lSecondsSinceStart;
    byte size = sizeof(longInt);

    byte arr[size];
    for (int i = 0; i < size; i++)
    {
        int iBitShift = 8 * (size - i - 1);
        if (iBitShift >= 8)
            arr[i] = ((longInt >> iBitShift) & 0xFF);
        else
            arr[i] = (longInt & 0xFF);
    }
    Wire.write(arr, size);
    g_bI2CSending = true;
}

void sendDataOverI2CGateway()
{
    switch(g_iOnRequestActionCode)
    {
        case 0:
            sendRainDataOverI2C();
            break;
        case 1: // send firmware version
            sendVersionDataOverI2C();
            break;
        case 2: // send operation time of arduino in seconds from start
            sendOperationTimeDataOverI2C();
            break;
        default: break;
    }
}

void defineOnRequestAction(int iBuffer) 
{
    while (Wire.available())
    {
        g_iOnRequestActionCode = Wire.read();
    }
}

这是我的python代码。 很简单,但是会引起一些头痛。

import smbus
import time
bus = smbus.SMBus(1)
while True:
        data = bus.read_i2c_block_data(0x04,0x02,4)
        result = 0
        for b in data:
                result = result * 256 + int(b)
        print(result)
        time.sleep(1)

执行我的python脚本后,我有时会收到此错误:

pi@WeatherStation:~/workspace $ sudo python readTimeOperationData.py
Traceback (most recent call last):
  File "readTimeOperationData.py", line 5, in <module>
    data = bus.read_i2c_block_data(0x04,0x02,4)
IOError: [Errno 121] Remote I/O error

有人可以帮助我解决此问题吗?

节食节食者

1 个答案:

答案 0 :(得分:0)

我解决了!!

我从这篇文章中得到了一个提示: https://www.raspberrypi.org/forums/viewtopic.php?t=203286

通过在bus = smbus.SMBus(1)之后添加延迟来解决此问题。 似乎需要某种程度的延迟才能使I2C稳定下来。

工作代码通过调用脚本100次而没有问题进行了测试。

import smbus
import time
bus = smbus.SMBus(1)
time.sleep(1) #wait here to avoid 121 IO Error
while True:
        data = bus.read_i2c_block_data(0x04,0x02,4)
        result = 0
        for b in data:
                result = result * 256 + int(b)
        print(result)
        time.sleep(1)
相关问题