在处理来自主设备的请求时,如何从从I2C设备读取字节?

问题描述 投票:0回答:1

我有一个Raspberry Pi Zero W作为主机,与作为从属的Arduino Pro Mini进行通信。我希望主人将命令发送到从属设备。但是,当我尝试使用主服务器上的命令(例如bus.write_byte_data或bus.write_byte)时,从站似乎只收到值255。这是代码:

Master(使用Python):

import time
import smbus

i2c_ch = 1
bus = smbus.SMBus(i2c_ch)

i2c_address = 20
bus.write_byte_data(i2c_address, 113,111)
val = bus.read_i2c_block_data(i2c_address,12)
bus.write_byte(i2c_address, 123)
print(val)

这是从站的requestEvent()(在Arduino C中:]

void requestEvent()
{
  byte command = Wire.read();
  Serial.println(command);
  command = Wire.read();
  Serial.println(command);
  command = Wire.read();
  Serial.println(command);
...
}

什么是一种方法,当从属设备发出命令时,从属设备可以接收字节?

python arduino raspberry-pi i2c
1个回答
1
投票

您可能正在尝试使用由Wire.onRequest创建的处理程序,而不是由Wire.onReceive创建的处理程序。一个onReceive处理程序将执行您想要的操作:

Wire.onReceive(receieveEvent);
Wire.onRequest(requestEvent);
...
void receieveEvent()
{
  Serial.println("received some data");
  while(0 < Wire.available()) // loop through all but the last
  {
    byte command = Wire.read();
    Serial.println(command);
  }
} 

PS:大声笑,你和我同名!

© www.soinside.com 2019 - 2024. All rights reserved.