Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I2C onReceive-handler called only once

Tags:

arduino

i2c

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?

like image 889
JorenHeit Avatar asked Dec 30 '14 12:12

JorenHeit


1 Answers

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;
}
like image 147
theUser Avatar answered Oct 29 '22 17:10

theUser