Receiving error when calling function in requestEvent() in I2C

I am using two arduino megas communicating through I2C with a slave-master relationship. i am sending two sensor data/variables both from master to slave and vice versa. the master code has compiled without any error but the slave code is giving an error when I call a function inside the requestEvent() saying

'IndexPosition' was not declared in this scope

how do I fix this error as the function is important to calculate sensor value

this is the slave code I'm using:

// Include library 
#include <Wire.h>
#include <Servo.h>

// Define Slave I2C Address
#define SLAVE_ADDR 9

// Define motor feedack pins
#define INDPOS A0
#define MIDPOS A1

// Define Slave answer size
#define ANSWERSIZE 2

// Define motor
Servo indfinger, midfinger;

// Define sending position array
byte Position[2];

// Define array for Recieved data
byte receivedAngle[2];

// Variable for received data
//int rd;


void setup() {

  indfinger.attach(9);
  midfinger.attach(8);
  
  // Initialize I2C communications as Slave
  Wire.begin(SLAVE_ADDR);
   
  // Function to run when data received from master
  Wire.onReceive(receiveEvent);

  // Function to run when data requested from master
  Wire.onRequest(requestEvent);
  
  // Setup Serial Monitor 
  Serial.begin(9600);
  Serial.println("I2C Slave Demonstration");
}


void receiveEvent() {
  // read one character from the I2C
  for (int i=0; i>2; i++){
    receivedAngle[i] = Wire.read();
  }
  // Print value of incoming data
  //Serial.println(rd);    
}

void requestEvent(){
  int IndexPosition = IndexFingerFunc();
  int MiddlePosition = MiddleFingerFunc();

  Position[0] = IndexPosition;
  Position[1] = MiddlePosition;

  for (int j=0; j<2; j++){
    Wire.write(Position[j]);
  }
  
}

void loop() {
  delay(50);

  Serial.println("Ind Angle: " + receivedAngle[0] + "   Mid Angle: " + receivedAngle[1]);
  indfinger.write(receivedAngle[0]);
  midfinger.write(receivedAngle[1]);

}

 int IndexFingerFunc() {
  int roboIndexAngle = analogRead(INDPOS);
  roboIndexAngle = map(roboIndexAngle, 65, 622, 0, 180);
  return roboIndexAngle;
}

int MiddleFingerFunc() {
  int roboIndexAngle = analogRead(MIDPOS);
  roboIndexAngle = map(roboIndexAngle, 65, 622, 0, 180);
  return roboIndexAngle;
}

Are you sure that you have posted the sketch that causes the error ?

Please post the full error message copied from the IDE using the "Copy error message" button

Yeah, it was the right sketch.
But strangely enough, I ran it once more just now and it compiled successfully. that was weird as the last 5 attempts showed the error above

There was never any reason for that sketch to give that error. IndexPosition is only declared and used in one function so it could not have been out of scope

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