2

Buttons on separate interrupt pins work fine (triggered on FALLING), bouncing is handling by forcing a 80ms lockout period during which further presses are ignored. I like that solution for being lightweight.

My goal is to have 1 interrupt handle all events (buttons and other digital inputs). I don't want to depend on loop(), I wish to be free to use delay often rather than timer interrupts.
Most buttons execute an action when pressed, some, while pressed.

What I have now (just 2 buttons for now):

schematic

simulate this circuit – Schematic created using CircuitLab

void setup() {
  pinMode(17, INPUT_PULLUP);
  pinMode(16, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(3), wotHappnd, CHANGE);
}

boolean isDebouncing(){
  unsigned int now = millis();
  if(now - time_lastPressed > time_debounceLockout){
    time_lastPressed = now;
    return false;
  }
  return true;
}

void wotHappnd(){
  boolean interruptFalling = digitalRead(3) == LOW;
  if(interruptFalling && isDebouncing()) return;
  // digitalRead the pins; do stuff
}

Internal pullups on all used pins.

My problem is that often (~4%), on interrupt, the interrupt pin is LOW all button pins are HIGH ("not pressed" - likely bouncing just as I read it). How to fix that?

Can't use delay during an interrupt; delayMicroseconds to wait for stable readout still feels inappropriate; a cap-based delay on the interrupt pin induces a period of floating. Prefer solutions in software or with no more than 1 extra component per input.

[edit] here's a claim that pin interrupts do some filtering already, which, if true, may make some solutions unreliable.

7
  • Can't you catch the button being pressed on the next bounce? Since the button bounces a few times, there should be one where it's LOW for long enough to catch. So in the code, you'll have to check if one of the buttons is pressed, before calling the isDebouncing function.
    – Gerben
    Jan 30, 2017 at 21:33
  • @Gerben It's a common debounce for all buttons. Sufficient for me. So, you're suggesting I do digitalRead in a loop until I get a LOW somewhere?
    – kaay
    Jan 30, 2017 at 21:41
  • No. Do two digital reads for the two buttons in the ISR. If both are high, do nothing. Otherwise execute the code you now have in the ISR.
    – Gerben
    Jan 30, 2017 at 21:49
  • Oh. Still, is it certain that a bouncing button will trigger effloads of interrupts? I'm asking because I read somewhere (Electrical Engineering StackExchange?) that there is already some signal stability assurance done on interrupts in some microcontrollers, to prevent exactly that. Plus, I have no idea what impact the diodes or other connected pins may have here, if any.
    – kaay
    Jan 30, 2017 at 22:03
  • 1
    I think you will find that in the end, thee best software debounced is none- a capacitor plus a resistor (or a terrible switch) will do wonders here.
    – dannyf
    Jan 30, 2017 at 22:19

2 Answers 2

1

In the Isr, read the two pins and maintain their current status (UN debounced), and reset a counter.

In the main loop, increment that counter. If it is more than a certain number, it means that the current state of the key has been stable for a while - bounce no more.

Or Google Kuhn debounced. I wrote a blog page about that. If you want, I can post it later. The basic idea is the same.

6
  • Thanks of reminding me of Kuhn debounce. Too bad it needs polling in main loop, which I don't want to do. Polling without delay won't produce the same result... maybe polling on a timer interrupt? Hmm...
    – kaay
    Jan 30, 2017 at 21:52
  • 1
    The approach I suggested is essentially the Kuhn debounced, without polling the buttons. Instead, you increment a counter as a way to detect stabilized buttons.
    – dannyf
    Jan 30, 2017 at 22:05
  • Sorry, I misunderstood before. Still, what puts me off is dependence on the main loop being free of long delays. Also, any idea about what's in the 4th comment under the question? Won't there be fewer CHANGE interrupts than changes on the (non-interrupt) button pin?
    – kaay
    Jan 30, 2017 at 22:17
  • 1
    There is no requirement for the main loop to have any delays, long Orr short
    – dannyf
    Jan 30, 2017 at 22:21
  • Any solution using loop() needs loop() to NOT have long delays. Kuhn repeats 10 times per second. Arduino is a prototyping platform - perfection is reserved for later, and in the meantime I tune my signal generation using delay.
    – kaay
    Jan 30, 2017 at 22:32
2

As ever I am the voice of dissent: never write software to solve a hardware problem.

For a double-throw switch the classic solution is an SR latch.

Single throw is actually harder. On the face of it, debounce is a trivial matter done with a capacitor and a pull-down (or pull-up) resistor. This will certainly stop floating and false positives from induced current from spikes. However, microprocessors switch pretty fast and will recognise the edges of microsecond oscillations around the switching voltage as changes of switch state. To prevent this you need the hysteresis of a Schmitt Trigger such as an LM7414 (TTL) or LM7417 (suitable for 3V3).

Here is the debounce circuit suggested in Understanding Schmitt Triggers. Unfortunately, it doesn't behave correctly under all conditions, for reasons explained on the Ganssle page referenced later.

Almost, but misbehaves under out of spec conditions

You can fix the problem with a diode. For TTL, R1 = 82kΩ, R2 = 18kΩ, C = 1µF

robust

Larger values of C will absorb slower bounces. One of my projects has a relay that bounces for so long I needed 470µF.

Here's what I regard as the last word on the subject — the Ganssle page. There's even a solution for multiple buttons on a single input. This is not quite the same as multiple buttons on a single interrupt but I think the approach may be applicable.

Note that on the Ganssle page a software solution is touted as cheaper than hardware. That's irrelevant for a one-off, true for mid sized runs and potentially false for mass produced items. Debugging software has its own costs and so does product recall. Make your decision in context. Arduino projects are usually one-off.

One objection to a hardware solution is cost, in assembly time, component count and board size. For hobby work that's a personal choice, and for commercial work it's a trade-off between simplicity and reliability. Reliability of software hinges on deterministic behaviour and the management of complexity. The Atmel chip doesn't have a lot of DRAM or program space, and moving this problem out of the software will make it smaller, simpler and more predictable.

That's not to say there aren't other ways to deal with the problem.

If you really want to do it in software you need to measure the pulse width and compare it to a threshold. Since you need both falling and rising edges for this, bind to CHANGE and test for state. The primary difference between this and the Kuhn method mentioned by others is it uses the clock instead of a counter allowing you to specify millisecond duration rather than iterations.

In the excerpt below, the listen flag is a simple alternative to noInterrupt() or unbinding the handler. My loop code evaluates a state machine transition function for current state and inputs, and not all states want input.

void isr_change()
{
    if (listen)
    {
        unsigned long now = millis();
        int d2 = digitalRead(2);
        if (d2 == LOW || fall_time == 0)
        { // FALLING
            fall_time = now;
        }
        if (d2 == HIGH)
        { // RISING
            command_pending = now - fall_time > MIN_PULSE_MS;
        }
    }
}

The state machine doesn't look at digital inputs, it looks at the command_pending flag, which is reset after the transition function finishes.

This is one of those things that looks simple, isn't, but does have a stock solution. It beats me why there isn't a mass produced debouncer component the way you can get op-amps.

Thank you to kaay in comments for referring me to the MC14490 which is a DIP16 or SOIC16 with six diode protected debouncers. Kaay thinks it's expensive but consider the cost of the time to code and debug debounce of six inputs. What about the cost when the program doesn't quite fit and you have to rewrite it to shrink it? And then regression test everything. Would you pay someone $5 for an instant guaranteed result that doesn't complicate or bloat your software? The economics change with production scale of course, but in very small runs I think it's well worthwhile.

I found the MC14490 DIP16 for 5USD and the SOIC for 9AUD online. Local shops didn't carry it.

6
  • One up and one down. Pity the down-voter couldn't be bothered to say why he thinks this is a poor answer.
    – Peter Wone
    Aug 21, 2019 at 13:17
  • I am not the downvoter, but I can see that hardware is more expensive than software in terms of parts, board real state, assembly time... Aug 22, 2019 at 11:42
  • @EdgarBonet I should hope you can see it, I discussed in explicitly in the penultimate paragraph.
    – Peter Wone
    Aug 23, 2019 at 23:02
  • 1
    +1 for effort. This answer gathers some nice ideas, and even if it's not a good match to the requirements in the question, it is useful. Although, gotta disagree with "(cost is) irrelevant for a one-off" - for most, slapping on a Shmitt&TheRest will cost from 20 minutes (in the unlikely case they have everything at hand) PLUS testing, to several hours. And that is ESPECIALLY hurtful if all you get is one unit. Debouncer ICs - I've had the exact same thought! As far as I'm concerned, at that price, MC14490 does not exist.
    – kaay
    Sep 13, 2019 at 22:49
  • 1
    @kaay perhaps, in many ways it's a values question. I suspect most Arduino projects are labours of love, where one of the deliverables is the satisfaction of both do it yourself and design it yourself. Given the negative reactions, I may be wrong about that. The reason I think a hardware debounce may be cheaper than software for a very small run is the cost of quality control for software and the cost of pushing firmware updates.
    – Peter Wone
    Sep 15, 2019 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.