Python中的SMBus/I2C在请求读取时一直触发接收回调

2024-06-16 13:39:08 发布

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

从我的PC机发出的一个回调请求,我是不是在尝试接收一个从微控制器读取的值呢?我运行的是I2C,因此SMBus似乎要慢得多。在

Arduino代码:

void dataReceive() {
    Serial.println("Receive");
}


void dataRequest() {
    Serial.println("Request");
    Wire.write(1);
}

void setup()
{
    Wire.begin(4);
    Wire.onReceive(dataReceive);
    Wire.onRequest(dataRequest);
}

PC代码:

^{pr2}$

我也有以下错误:

Traceback (most recent call last):
  File "./i2ctest.py", line 16, in <module>
    data = bus.read_i2c_block_data(0x04, 0x09, 1)
IOError: [Errno 11] Resource temporarily unavailable

虽然我可以在Arduino串行监视器中看到dataReceive回调被触发。在


Tags: 代码datarequestseriali2carduinowritereceive
1条回答
网友
1楼 · 发布于 2024-06-16 13:39:08

Arduino在Wire.h库中没有重复的启动信号。你的解决方案是这样的:

在Arduino一侧:

void dataReceive() {
    x = 0;
    for (int i = 0; i < byteCount; i++) {
        if (i==0) {
            x = Wire.read();
            cmd = ""
        } else {
            char c = Wire.read();
            cmd = cmd + c;
        }
    }
    if (x == 0x09) {
        // Do something arduinoish here with cmd if you need no answer
        // or result from Arduino
        x = 0;
        cmd = ""
    }
}

这将把接收到的第一个字符存储为“命令”,然后剩下的字符将作为参数部分。在您的例子中,命令是0x09,参数是1。在

在PC端,python命令是:

^{pr2}$

其中buff为“1”。在

您可能需要datarequest事件:

^{3}$

这将返回一个简单的FF。在

如果您需要来自arduino的答案,那么在这里处理cmd参数。在这种情况下,在python端,您需要更多:

bus.write_i2c_block_data(0x05,0x09,buff)
tl = bus.read_byte(0x05)

这会将“1”发送到命令“0x09”到设备“0x05”。然后简单地用“0x05”命令从设备获取答案。在

相关问题 更多 >