Suspected problem with variable scope.

Hi,

I’m trying to write a sketch that will turn on an led when an IR sensor reads above a certain value. My problem is coming when trying to introduce a calibration where a limit is set using an ambient reading of IR. Currently the LED is always staying on whereas if i manually change the limit to a value of 350 for example it is working as intended (i.e turning on when an IR source is brought near the sensor). I think that the problem may be something to do with the scope of “limit” variable. I’m still very new to Arduino and C and would appreciate any help someone could give.

My code is:

int led = 2;                 //LED A1 to digital pin 2
int sensor = 0;             //Readings from sensor A1 to analog pin 0
int limit;


void setup()
{
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);                  //set the LEDs in off mode (initial condition)
  Serial.begin(9600);                      //setting serial monitor at a default baud rate of 9600

  int calibration = analogRead(sensor);    //taking calibration readings of ambient IR
  int limit = calibration + 300;           //creating limits of ambient IR + 300
  
}
void loop()
{
  int val = analogRead(sensor);

  if (val >= limit) {              //If sensor reading is greater than the limit
    digitalWrite(led, HIGH);      //LED will be in ON state
    delay(20);
  }
  else if (val < limit)            //If sensor reading is lower than the limit
  {
    digitalWrite(led, LOW);         //LED will be in OFF state
    delay(20);
  }
}

Thanks!

int led = 2;                 //LED A1 to digital pin 2
int sensor = 0;             //Readings from sensor A1 to analog pin 0
int limit;   ///////////  The scope of this one is fine


void setup()
{
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);                  //set the LEDs in off mode (initial condition)
  Serial.begin(9600);                      //setting serial monitor at a default baud rate of 9600

  int calibration = analogRead(sensor);    //taking calibration readings of ambient IR
  int limit = calibration + 300;   //////  This one disappears on the next line when setup exits
  
}

You want to use the one that is global. When you put the "int" in front, it creates a new variable with the same name. That variable is limited to setup and goes out of scope at the very next line when setup exits.

Lose the "int" on the last line in setup.

Which limit variable do you mean ? You have one global version declared at the start of the program that will be visible to all sections of the program and another one declared in the setup() function and only visible to code in that function.

Delete the int from

 int limit = calibration + 300;           //creating limits of ambient IR + 300

in setup() and the global variable will be used throughout the program.

Thank you both! This solved my problem and makes a lot of sense.