Finding a counter that restarts

A detector produces one HIGH interval per object and reads LOW between objects. Every interval and intervening LOW is sampled, and the detector initially reads LOW. An indicator should turn on after four objects have been counted and remain on. The test ends before the count reaches 1000.


The sketch below never accumulates the required total:


C++
bool previousHigh = false;

void setup() {
  pinMode(8, INPUT);
  pinMode(12, OUTPUT);
  digitalWrite(12, LOW);
}

void loop() {
  int count = 0;
  bool isHigh = (digitalRead(8) == HIGH);
  if (isHigh && !previousHigh) {
    count++;
  }
  previousHigh = isHigh;
  digitalWrite(12, count >= 4 ? HIGH : LOW);
}


Which single change fixes the cumulative counting behavior while preserving detection of each new HIGH interval?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Arduino Programming Questions: