Hacker News new | ask | show | jobs
by HALtheWise 1280 days ago
Nice project!

> Due to debouncing troubles, it seems to be double-reading each pulse. At some point I should throw a scope on it to confirm what the problem is, but it works quite adequately as-is. (My first try only had a 10ms delay, which empirically resulted in septuple-reading each pulse…)

Needless to say, this is not the canonical way to count pulses. A more typical and accurate loop would look like

  if digitalRead(pin):
      count +=1 # register the pulse
      sleep(0.01)  # debouncing delay 
      while digitalRead(pin):  # wait for end of pulse
          pass
      sleep(0.01)  # debouncing delay
2 comments

I’m more used to “while pin hot in the last devounceDelay consider held” approach. This double sleep method has a larger minimum for a given debounce delay and triggers multiple presses if you get any contact drops at all during a long hold. Not sure if there are other upsides I’m missing though.
I'm curious, why the first sleep? Why not go into the while loop right away?
The while condition is reading the pin. The first delay lets the pin stabilize before waiting for the pin to go false.