I2C onReceive handler called only once

I'm having trouble communicating between Arduino over I2C. For some reason, the onReceive handler onReceive called only 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 for the sender to send bytes every second and let the receiver act on this by typing a message. However, the message is printed only once. When I reset the slave, it prints again, but only once.

Any ideas this might come from?

+5
source share
1 answer

You must make sure that you read all the bytes from the stream. Another wise seems to block. Make an event handler this way. Therefore, you can call it several times.

 void takeAction(int nBytes) { Serial.println("Action!"); while(Wire.available()) { Wire.read(); } return; } 
+4
source

Source: https://habr.com/ru/post/1210101/


All Articles