Skip to main content
 首页 » 编程设计

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

2025年05月04日14linjiqin

我试图通过从我的 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”读取命令即可获取答案。