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.

You need a variable, let's call it count. Then in the code where you turn off the LED, add one to that variable. Print it wherever in your code you would like.

If you want advice more specific to your particular situation, then post the code you are using.

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.

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:

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

OK, so add

int count = 0;

And inside the block where you are blinking the light, put:

count = count + 1;

or the shorthand version:


Then put a statement somewhere to print that and you're done.

I would strongly advise you go and find a basic C++ tutorial online. Things will be a little different there because they will be focused on writing code for computers with screens and use cout instead of Serial.print and stuff like that. But the stuff about variables and statements is crucial to learn.

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.