Hello guys,
i am trying to establish a I2C connection between 2 Arduino Megas.
I created a code for the master that sends an array of 15 bytes.
The slave should receive it and print it out on the serial.
Master:
#include <Wire.h>
int ang = 1;
int speed_vl = 2;
int speed_vr = 3;
int speed_hl = 4;
int speed_hr = 5;
int current_vl = 6;
int current_vr = 7;
int current_hl = 8;
int current_hr = 9;
int emp_1 = 8;
int emp_2 = 7;
int emp_3 = 6;
int emp_4 = 5;
int emp_5 = 4;
int emp_6 = 3;
void setup() {
Wire.begin();
}
//int x = 3094;
//int x1 = (x >> 8) & 0xFF;
//int x2 = x & 0xFF;
//int y = 10;
//int z = 20;
//byte msg[] = {x1, x2, y, z};
byte msg_send[] = {ang, speed_vl, speed_vr, speed_hl, speed_hr, current_vl, current_vr, current_hl, current_hr, emp_1, emp_2, emp_3, emp_4, emp_5, emp_6};
void loop() {
Wire.beginTransmission(8);
Wire.write(msg_send,15);
Wire.endTransmission();
delay(500);
}
Slave:
#include <Wire.h>
int i = 0;
int x[] = {};
void setup() {
Wire.begin(8);
Wire.onReceive(receiveEvent);
Serial.begin(9600);
}
void loop() {
delay(100);
}
void receiveEvent(int howMany) {
while (1 <= Wire.available()) {
int c = Wire.read();
Serial.print(c);
x[i]=c;
i++;
}
Serial.println();
}
This is working fine, but it oft loses data. "123456789876543" is the right message.
Serial Log:
123456789876543
123456789876543
12
12123000000000000
123456789876543
123456789876543
123456789876543
123456789876543
12
12123000000000000
123456789876543
123456789876543
Serial Log w/o delay() on both Master/Slave:
123456789123000000000000
123456789123000000000000
123456789123000000000000
123456789123000000000000
123456789123000000000000
123456789123000000000000
123456789123000000000000
123456789123000000000000
123456789123000000000000
Why does it loses data when running with both delay()’s? And why does it only print it right until the 9th Byte and fills it with 0’s when commenting out both delay()’s?
I want them to communicate as fast as possible without losing data. What is the best way for doing it?
Thank you in advance.
Greets.
EDIT: Connections: SCL to SCL, SDA to SDA, 5V to 5V, GND to GND, and one arduino connected to the PC with a usb cable. No external Pull Ups.