LED blinking count with LDR sensor How to count +1 all the time if LED blinks with LDR sensor

Image:


If i turn on led it must count into serial monitor 1 and if i turn off led and turn on again then it counts 2.

To turn on led I must put my hand into LDR sensor.

It also looping text in serial monitor "First LDR sensor is Dark".

int ledPin1 = 7;   
int ledPin2 = 8;  
int ledPin3 = 9;   
int ldrPin1 = A0;  
int ldrPin2 = A1;
int ledTest = 200;
int ldrStatus1 = 0;
int ldrStatus2 = 0;
int ledCheck1 = 0;
int ledCheck2 = 0;
int Count = 0;

void setup() {

  Serial.begin(9600);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);

  pinMode(ldrPin1, INPUT);
  pinMode(ldrPin2, INPUT);
}

void loop() {

  ldrStatus1 = analogRead(ldrPin1);
  ldrStatus2 = analogRead(ldrPin2);

   if (ldrStatus1 &lt;= ledTest) {
    digitalWrite(ledPin1, HIGH);               
    Serial.println("First LDR is Dark");
    ledCheck1 = 1;
    Count++;
    Serial.println(Count);
   } else {
    digitalWrite(ledPin1, LOW);  
    ledCheck1 = 0;
   }

   if (ldrStatus2 &lt;= ledTest) {
    digitalWrite(ledPin3, HIGH);               
    Serial.println("Second LDR is Dark");
    ledCheck2 = 1;
    Count++;
    Serial.println(Count);
   } else {
    digitalWrite(ledPin3, LOW);
    ledCheck2 = 0;
   }

   if ((ledCheck1 == 1) &amp;&amp; (ledCheck2 == 1)) {
    digitalWrite(ledPin2, HIGH);
    Count++;
    Serial.println(Count);
   } else {
    digitalWrite(ledPin2, LOW);
   }

}


At the moment it counts when it is turned on, like seconds..
How to fix or make it work correctly?
Use state change detection and hysteresis for counting pulses in an analog signal.

const int lowerThreshold = 150;
const int upperThreshold = 200;

const uint8_t analogPin = A0;
const uint8_t ledPin = LED_BUILTIN;

void setup() {
  Serial.begin(115200);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  static bool state = LOW;
  static unsigned int counter = 0;

  int analogValue = analogRead(analogPin);
  if (state == HIGH) {
    if (analogValue &lt; lowerThreshold) {
      state = LOW;
      counter++;
      Serial.println(counter);
      digitalWrite(ledPin, LOW);
    }
  } else { // state == LOW
    if (analogValue &gt; upperThreshold) {
      state = HIGH;
      digitalWrite(ledPin, HIGH);
    }
  }
}


This sketch basically applies a software Schmitt trigger to the analog input signal, and increments the counter on each falling edge. (Rising edge of light intensity, because your LDR configuration inverts the signal.)


The red waveform is the analog input from the LDR. The gray rectangular wave is the state (and the state of the LED). The counter is incremented at each black, vertical dashed line.