Help with coding - IRSensor with LED

Hello,

I need some help with coding on my Arduino Uno board. I am using IRSensor as the controller to my LEDs, the idea is that when the sensor senses the object within a certain proximity, I want the light to turn on or off. When the light is off, with approaching it you can turn it on, and when the light is on, Vise Versa.
Here is the code I've written, when I tried it, the light will turn off but it won't turn back on.

Please let me know if you have a solution for this. Thank you so much.

int IRSensor = 2; // connect ir sensor to arduino pin 2
int LED = 12; // conect Led to arduino pin 13
int timeNumber = 0;
boolean timeState = true;

void setup()
{
 pinMode (IRSensor, INPUT); // sensor pin INPUT
 pinMode (LED, OUTPUT); // Led pin OUTPUT
}

void loop()
{
 if (timeState == false){
   digitalWrite(LED, LOW);
 }else{
   digitalWrite(LED, HIGH);
 }

 int statusSensor = digitalRead (IRSensor);

 if (statusSensor == 1){
   timeNumber++;
   if(timeNumber == 9){
     if(timeState == false) timeState = true;
     if(timeState == true) timeState = false;
     timeNumber = 0;
   }
 }
 
 delay(100);
}
int LED = 12; // conect Led to arduino pin 13

The outdated comment is worse than useless.

     if(timeState == false) timeState = true;

if(timeState == true) timeState = false;

Read this through. Slowly.

If timeState is false, make it true.

If it's true (yes it is, since we just made it true) then make it false again.

A quick way to "toggle" or make it the opposite of what it was, is to use the "not" operator. This is usually written in C code with the "!" symbol. Every time you see "!" say "not" in your head.

  timeState = !timeState;

Hi,
What IRsensor are you using?
Can you post a link to data/spec?
Can you post a picture of your project including the sensor?

Thanks.. Tom.. :slight_smile: