I2C - onRequest not working

Hi,

I’m looking for possible reasons why “onRequest()” will not work. Whenever I send a request to my Arduino “onRequest()” does not execute, instead “onReceive()” executes and I receive the register address that I have queried.

I’m not 100% sure if im using 7bit or 8bit I2C, I do know that I have attempted using addresses 0~255 and my Arduino recieves commands successfully.

I modified the sample code to test this:

#include <Wire.h>

void setup()
{
  Wire.begin(42);                // join i2c bus with address #42
  Wire.onRequest(requestEvent); // register event
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
  Serial.println("I2C Test");
}

void loop()
{
  delay(100);
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent()
{
    Wire.write("AB"); // respond with message of 2 bytes
    Serial.println("Request Recieved");
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
  Serial.println("Command Recieved");
 
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
  while(0 < Wire.available()) // loop through all but the last
  {
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  Serial.println();
}

I found issues when using Serial.print(ln) statements in request handlers. Once I took them out it worked better.

void requestEvent()
{
    Wire.write("AB"); // respond with message of 2 bytes
    Serial.println("Request Recieved");
}

The onRequest handler is (called from) an ISR (interrupt service routine). It is not recommended to do Serial.prints inside those in general, and in particular with I2C because you will delay the response possibly causing the transaction to time out.

Ditto for the receive event.