Hello Everyone!
I am trying to make a sort of two way communication with two arduinos, a Mega (master) and a nano(slave). The main problem I have is that it seems like the arduino nano which has the slave code, the wire.onReceive() seems to not be working... I can't figure out what is wrong with the code. Here are the two codes:
MASTER:
#include <Wire.h>
#define SLAVE_ADDRESS 0x04
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial communication at 9600bps
}
void loop() {
Wire.beginTransmission(SLAVE_ADDRESS); // transmit to slave device
Wire.write(0x00); // sends one byte
Wire.endTransmission(); // stop transmitting
delay(10);
Wire.requestFrom(SLAVE_ADDRESS, 6); // request 6 bytes from slave device
while(Wire.available()) { // slave may send less than requested
char c = Wire.read(); // receive a byte as character
Serial.println(c); // print the character
}
delay(500); // wait half a second
Wire.beginTransmission(SLAVE_ADDRESS); // transmit to slave device
Wire.write(0x01); // sends one byte
Wire.endTransmission(); // stop transmitting
delay(10);
Wire.requestFrom(SLAVE_ADDRESS, 6); // request 6 bytes from slave device
while(Wire.available()) { // slave may send less than requested
char c = Wire.read(); // receive a byte as character
Serial.println(c); // print the character
}
delay(500); // wait half a second
}
SLAVE:
#include <Wire.h>
int flag = 0;
#define SLAVE_ADDRESS 0x04
void setup() {
Wire.begin(SLAVE_ADDRESS); // join i2c bus with address
Wire.onReceive(receiveEvent); // register receive event
Wire.onRequest(requestEvent); // register request event
}
void loop() {
delay(100);
}
void receiveEvent(int numBytes) {
int c;
while(Wire.available()) {
c = Wire.read(); // receive byte as a character
Serial.print(c); // print the character
}
if(c == 0x00) flag = 1;
else if (c == 0x01)flag = 0;
}
void requestEvent() {
if(flag == 0) Wire.write("hello!");
else if(flag == 1) Wire.write("bye!");
}
Thank you!