The below two sketches are the basic form of WIRE I'm using between two Arduinos.
I started getting a lot of garbage instead of my data when I added more lines between
requestEvent() {
and
Wire.write("hello ");
My guess is the lines take too long to exicute, throwing the bits off where they should land.
How is WIRE properly timed? How can I make sure it stays correct?
These lines:
Wire.requestFrom(8, 6);
while (Wire.available()) {
char c = Wire.read();
don't make sense to me. For if the data hasn't been received yet, "available()" will fall through and nothing be read. There is nothing to time when "available" will be exicuted, too soon or too late.
And my problem seems to be with the timing between "requestEvent" and "Wire.write", how soon? How late?
I'm sure it's been designed with a way to keep everything timed exactly right.
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}
void loop() {
Wire.requestFrom(8, 6); // request 6 bytes from slave device #8
while (Wire.available()) { // slave may send less than requested
char c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character
}
delay(500);
}
#include <Wire.h>
void setup() {
Wire.begin(8); // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
}
void loop() {
delay(100);
}
// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
Wire.write("hello "); // respond with message of 6 bytes
// as expected by master
}