Using data from Wire library in other functions

Hi,

I am currently receiving data from another Arduino via I2C/Wire library and I would like to use the received data in a different function. (a function to transmit the bytes I receive via LoRa)

void receiveEvent() {
    byte x = Wire.read();    
    Serial.print(char(x)); 
}

How can I access byte x from this function? I have already tried to use byte as a return type, but since I have declared:


    Wire.begin(8);        // join i2c bus 
    Wire.onReceive(receiveEvent);

I don't get the value I want to see.

Something like below might do the job.

byte x;
bool I2Cready;

void setup()
{
  ...
  ...
}

void loop()
{
  ...
  ...
  if(I2Cready == true)
  {
    Serial.print(char(x)); // print char
    I2Cready = false;
  }
}

void receiveEvent()
{
  x = Wire.read();    // receive byte
  I2Cready = true;
}

Don't use single letter global variables. Instead of x, use e.g. receivedI2Cdata.

I'm not sure if the variables in receiveEvent need to be volatile.

Not tested

1 Like

It works! Thank you :smile:

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.