Wednesday, February 2, 2022

[SOLVED] How to send an array by i2c?

Issue

I've been trying for several days now to send a python array by i2c.

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) 

In the function above: addr - arduino i2c adress; cmd - Not sure what this is; array - python array of int numbers.
Can this be done? What is actually the cmd?


FWIW, Arduino code, where I receive the array and put it on the byteArray:

void receiveData(int numByte){
    int i = 0;
    while(wire.available()){
        if(i < 4){
            byteArray[i] = wire.read();
            i++;
        }
     }
  }

It gives me this error:
bus.write_i2c_block_data(i2c_adress, 0, decodedArray) IOError: [Errno 5] Input/output error.
I tried with this: bus.write_byte(i2c_address, value), and it worked, but only for a value that goes from 0 to 127, but, I need to pass not only a value, but a full array.


Solution

It took me a while,but i got it working.

On the arduino side:

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();
      }
    }
}  

On the raspberry side:

def writeData(arrayValue):

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

And that's it.



Answered By - SnackK
Answer Checked By - Mary Flores (WPSolving Volunteer)