Using IR sensor to count

Greeting Arduino Geniuses ,

I am new to this forum and trying to learn arduino programming.

I am Seeking your kind advice and guidance on the following problem i am facing.

  1. Every time my IR sensor encounters an obstacle it switches OFF my LED light..

Question: How can i count how many times the LED is turning OFF and show the result in
Serial.println?

kind regards
Lord Stark.

Use an unsigned int (or long) as a counter. When you switch off the led, increment the counter.

Is your serial monitor always connected? If so, that is it. Remember that opening serial monitor will result in a reset when using e.g. a Nano or Mega and the result will be incorrect; which board are you using?

Do you need to remember after a reset / power cycle?

Dear Delta_G and sterretje

Thank you so much for your kind replies. You guys are AMAZING.

This is the Sketch i am trying to write for my Arduino UNO.

/*with this sketch

  • IR sensor will keep the LED on and when object is detected
  • the light will be off and start again.
  • THIS IS TEST CODE
    */

int led = 11; // declaring LED to pin 11 of Arduino.
int ledOff; // declaring LED Off open integer .

void setup() {
// put your setup code here, to run once:
pinMode(A0,INPUT);
pinMode(A1,OUTPUT);
pinMode(A2,OUTPUT);
pinMode(led,OUTPUT);
digitalWrite(A2,HIGH);
digitalWrite(A1,LOW);
Serial.begin(9600);
}

void loop () {
// put your main code here, to run repeatedly:
Serial.println(analogRead(A0)); // this will print the IR sensor value.
delay(100); // printing delay.

if(analogRead(A0) < 250) // less then 250 means there is an obstacle
{digitalWrite(11,LOW); // LED will be OFF
delay (5000); // LED off for 5 seconds
digitalWrite (11,HIGH); // LED ON again
delay (3000);} // for 3 seconds

else // if IR doesnt sense an obstacle
digitalWrite(11,HIGH); // LED will be ON continiously
}

Thank you Mr Delta_G.

Your kind advice has made my program to work. its is now counting how many time the LED is Off.

Thank you for suggesting about C++. I only started learning about arduino from youtube tutorial.