python - Python 中的 SMBus/I2C 在请求读取时不断触发接收回调

标签 python arduino i2c

我试图通过从我的 PC 发送读取请求来从 Arduino 微 Controller 读取一些值,但它没有触发请求回调,而是触发了接收,这根本没有意义吗?我正在运行 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);
}

电脑代码:

import smbus
bus = smbus.SMBus(1)

data = bus.read_i2c_block_data(0x04, 0x09, 1)
print data

我也收到以下错误:

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 回调。

最佳答案

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 命令是这样的:

bus.write_i2c_block_data(0x05,0x09,buff)

buff 为“1”。

您可能需要数据请求事件:

void dataRequest() {
    x = 0;
    Wire.write(0xFF);
}

这将发回一个简单的 FF。

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

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

这会将“1”发送到命令“0x09”到设备“0x05”。然后,您只需从设备“0x05”读取命令即可获取答案。

关于python - Python 中的 SMBus/I2C 在请求读取时不断触发接收回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28086495/

相关文章:

python - 按给定的自定义顺序对列表进行排序

python - Numpy 矩阵乘法 U*B*U.T 导致非对称矩阵

python - 计算两个不同数字的倍数之间的差

arduino - macOS X Mojave 10.14 Beta FTDI USB 串行驱动程序

linux - 如何在 Linux 上模拟 I2C 设备?

c - STM Nucleo I2C 未发送所有数据

python - 错误,删除 EPD 后使用已弃用的类 PySimpleApp

php - 如何使用 PHP 和 Arduino IDE 通过 arduino 创建 AI?

Arduino 独立版

c - 写入()到 i2c 设备 : Operation not permitted