Debounce occasionally missing signal

Hello!

Seeking assistance with what I thought to be a simple program. I am trying to monitor a 12v digital signal from a motion detector through an optoisolator (see attached) and counting the pulses (~200ms HIGH, with small initial bounce). However, my code seems to unpredictably miss the occasional pulse. Some register, while others are missed. I have not been able to detect a pattern. I've scoured my code for delays that may be causing the unit to be unresponsive to no avail. I've been investigating various debounce methods but none seem to resolve the issue.

I'm a relative novice to Arduino programming, so am not ruling out the possibility of some silly oversight. Any advice would be incredibly appreciated.

Code counting pulses with one of my debounce attempts:

  int val = digitalRead(entryIn);
  delay(10);
  int val2 = digitalRead(entryIn);
  if (val == val2) {
    entryState = val;
    if (entryState != entryLast) {
      if (entryState == HIGH) {
        occupancyCount++;
        reportOccupancy();  // prints occupancyCount to display and blinks some LEDs
      }
    }
    entryLast = entryState;
  }

Complete sketch attached.

As I am a novice, there is a good chance I've left out relevant information. My apologies. Will gladly provide any additional circuit or sketch references as necessary.

Thank you!

optoisolator.jpg

sketch_counter.ino (9.47 KB)

Please show all of your sketch.

There are a number of examples of how to debounce in software on the Internet and a Google search will find more than you really want to know about.
Just remember that a switch can bounce for anything up to 100mSec (these tend to be bad switches). The code I use generally tests each mSec and requires that there are 10 consecutive values that are the same for the switch input to be "debounced".
Susan

I don't see where you're getting a bounce in a solid state system in the first place: I thought bounce was a mechanical phenomenon.

But that aside, an easy way to handle debouncing is to use the bounce2 library.