Transferring char array through I2C communication

Hi everyone,
I tried to send char array from one Arduino to next via I2C communication. My sending sketch is,

#include <Wire.h>

const int16_t I2C_MASTER = 0x42;
const int16_t I2C_SLAVE = 0x08;

char Data1[54] = "$GNSS,0,0,0,0000000000,0000000000,0000000,00,********";
char Data2[54] = "$ECEF,0000000000,0000000000,000000000,00000000,000000";

void setup()
{
  Serial.begin(115200);
  Wire.begin();
}

void loop() {
  
  Serial.println(Data1);
  Serial.println(Data2);
  Wire.beginTransmission(8);
  Wire.write(Data1);
  Wire.endTransmission();
  delay(100);
  Wire.beginTransmission(8);
  Wire.write(Data2);
  Wire.endTransmission();
  delay(500);
}

And my receiver sketch is,

#include <Wire.h>

void setup() {
  Wire.begin(8);                
  Serial.begin(115200);           
}

void loop() {
  Wire.onReceive(receiveEvent); 
  delay(100);
}
void receiveEvent(int howMany) {
  
  while (1 < Wire.available()) { 
    char c = Wire.read(); 
    Serial.print(c);         
  }
  int x = Wire.read();    
  Serial.println(x);   
}

My sender side Serial monitor is OK. But my receiver side is showing like this,

$GNSS,0,0,0,0000000000,0000000048
$ECEF,0000000000,0000000000,00048

How can I pass whole array via I2C. I tried using Wire.write(Data1, sizeof Data1); but gives same result. I hope to pass some sensor data from one Arduino to next and doing calculation in my second Arduino. Please help me to fix this problem.

The 8 bit Arduinos are no good I2C slaves. Which Arduinos/controllers do you use?

The I2C buffers are limited (32 bytes?) so you have to split your transmissions.

Try to transfer all data byte by byte.

That's what was to be expected. The I2C interface is not a direct replacement of a UART communication. The send/receive buffer is 32 bytes so everything bigger than this must be split into enough corresponding Wire.beginTransmission()/Wire.endTransmission() rounds.

I don't see the reason why you receive the last byte of every transmission as an integer but all others as characters. There is no comment in your code so you might have to explain that to us.

I have the impression you're abusing the I2C interface for a task that should be done by another type of interface (probably UART).

The Wire.onReceive() call should go into setup(). The receiveEvent() routine is called in interrupt context so you must not use any routine depending on interrupts (such as Serial.print())!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.