关于python:如何通过i2c发送数组?

How to send an array by i2c?

我已经尝试了几天,以通过i2c发送python数组。

1
2
3
4
data = [x,x,x,x] #`x` is a number from 0 to 127.
bus.write_i2c_block_data(i2c_address, 0, data)

bus.write_i2c_block_data(addr, cmd, array)

在上面的函数中:addr-arduino i2c地址; cmd-不确定这是什么; array-整数类型的python数组。 能做到吗? 什么是cmd?

FWIW,Arduino代码,在此处接收数组并将其放在byteArray上:

1
2
3
4
5
6
7
8
9
void receiveData(int numByte){
    int i = 0;
    while(wire.available()){
        if(i < 4){
            byteArray[i] = wire.read();
            i++;
        }
     }
  }

它给了我这个错误:bus.write_i2c_block_data(i2c_adress, 0, decodedArray) IOError: [Errno 5] Input/output error.我尝试了这个错误:bus.write_byte(i2c_address, value),它起作用了,但仅适用于从0到127的value,但是,我不仅需要传递值,还需要传递完整的 数组。


功能是好的。

但是您应该注意以下几点:

  • bus.write_i2c_block_data(addr,cmd,[])发送cmd的值以及I2C总线上列表中的值。

所以

1
bus.write_i2c_block_data(0x20, 42, [12, 23, 34, 45])

不会向设备发送4个字节,而是发送5个字节。

我不知道线库如何在arduino上工作,但是设备仅读取4个字节,它不发送最后一个字节的ACK,并且发送方检测到输出错误。

  • I2C设备地址存在两种约定。 I2C总线具有用于设备地址的7位和用于指示读或写的位。另一个(错误的)约定是用8位写入地址,并说您有一个要读取的地址,另一个有要写入的地址。 smbus软件包使用正确的约定(7位)。

示例:0x23以7位格式表示,写入时变为0x46,读取时变为0x47。


我花了一段时间,但我开始工作了。

在arduino方面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int count = 0;
...

...
void receiveData(int numByte){

    while(Wire.available()){
      if(count < 4){
        byteArray[count] = Wire.read();
        count++;
      }
      else{
        count = 0;
        byteArray[count] = Wire.read();
      }
    }
}

在覆盆子方面:

1
2
3
4
def writeData(arrayValue):

    for i in arrayValue:
        bus.write_byte(i2c_address, i)

就是这样。