passing a variable to another event

there is a variable in receiveEvent(); which is called “x” in the attached file.
I want this x be subtracted from value_1 which is in the main loop event. what should I do to pass the “x” variable to the main loop so that the calculation can be done?

i2c_slave_passvar.ino (428 Bytes)

emrahyigit: there is a variable in receiveEvent(); which is called "x" in the attached file. I want this x be subtracted from value_1 which is in the main loop event. what should I do to pass the "x" variable to the main loop so that the calculation can be done?

make Value_1 a global variable and the function will have access to it.

See the comments in the code. Have a look at this page that has information on variable scope in C++.

#include <Wire.h>

byte x = 0;  // create a global variable for x,  the entire sketch has 
              // access to global variables

void setup() {
  Wire.begin(1);                
  Wire.onReceive(receiveEvent); 
  Serial.begin(9600);           
}

void loop() {
  byte value_1=analogRead(A1);
  delay(100);
  result=Value_1-x;
  if (Result>........
}

void receiveEvent(int howMany) {
  while (1 < Wire.available()) { 
    char c = Wire.read(); 
    Serial.print(c);        
  }
  x = Wire.read();   // remove the type definition. Otherwise creates another variable
                     // named x
  Serial.println(x);         
}

thank you very much. the key sentence for me is

x = Wire.read(); // remove the type definition. Otherwise creates another variable
// named x
Serial.println(x);

because İ also put the type definition in the loop.