Hi everyone, I am writing Master/Slave I2C program on two Teensy boards.
The master sends some data to the slave and then requests some data from it.
I noticed that in my code, when the master requests data from slave, it also somehow triggers the onReceive event on the slave. Here is the master code:
#include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(115200);
delay(500);
}
void loop()
{
Serial.println("Sending");
Wire.beginTransmission(10);
Wire.write("12345");
Wire.endTransmission();
Serial.println("Sent");
delay(5000);
Serial.println("Requesting");
Wire.requestFrom(10, 2);
while(Wire.available())
{
char c = Wire.read();
Serial.print(c);
}
Serial.println();
Serial.println("Requested");
delay(5000);
}
And the code for slave:
#include <Wire.h>
void setup()
{
Serial.begin(115200);
delay(500);
Wire.begin(10);
Wire.onRequest(requestEvents);
Wire.onReceive(receiveEvents);
}
void loop(){}
void requestEvents()
{
Wire.write("OK");
}
void receiveEvents(int howMany)
{
char c[10];
c[0]='\0';
int index=0;
while(Wire.available())
{
c[index++]=Wire.read();
}
c[index]='\0';
if((howMany!=5)||(strlen(c)!=5)) // Just so that there is no Serial activity
// in the interrupt routine when everything is normal.
{
Serial.printf("wrong: %d: '%s'\r\n",howMany,c);
}
}
When the code is run, I open serial monitor on both devices and I see that as soon as the master shows:
Requesting
OK
Requested
the slave shows:
wrong: 7: '1234555'
Master is a Teensy 4.1 and the slave in a Teensy 3.6.
I also checked the I2C lines on a logic analyzer and the extra send is not happening on the physical lines, so it is only something in the code for slave.
Any help is greatly appreciated.