I'm having trouble communicating between Arduino's over I2C. For some reason, the onReceive
handler is only called once.
Master Code (sender):
#include <Wire.h>
#include "i2csettings.h" // defines address
void setup()
{
Wire.begin(I2C_MASTER_ADDRESS);
}
void loop()
{
Wire.beginTransmission(I2C_SLAVE_ADDRESS);
Wire.write(0x11);
Wire.endTransmission();
delay(1000);
}
Slave Code (receiver):
#include <Wire.h>
#include "i2csettings.h"
void takeAction(int);
void setup()
{
Serial.begin(9600);
Wire.begin(I2C_SLAVE_ADDRESS);
Wire.onReceive(takeAction);
}
void loop()
{}
void takeAction(int nBytes)
{
Serial.println("Action!");
}
The idea in this test-setup is to have the sender send a byte every second, and let the receiver act on this by printing a message. However, the message is only printed once. When I reset the Slave, it's printed again, but just once.
Any ideas where this may come from?
You have to make sure you read all the bytes from the stream. Other wise it seems to block. Make your event handler look like this. So you can call it multiple times.
void takeAction(int nBytes)
{
Serial.println("Action!");
while(Wire.available())
{
Wire.read();
}
return;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With