9 ms·
How to Debounce a Contact (2014)
- user_7832 2y agoI saw this site in one of the comments on https://hackaday.com/2025/01/04/button-debouncing-with-smart-interrupts/ https://hackaday.com/2025/01/04/button-debouncing-with-smart...
- dekhn 2y agoI've been given a lot of suggestions for debouncing switches over the years. I'm just doing hobby stuff, either I have an endstop switch for some CNC axis, or more recently, some simple press buttons to drive a decade counter or whatever. My goal for one project was just to have a bit counter that I could step up, down, reset, or set to an initial value, with no ICs (and no software debounce). I got lots of different suggestions, none of which worked, until I found one that did: 1) switch is pulled high or low as needed 2) switch has capacitor to ground 3) switch signal goes through a schmitt trigger I designed this into its own PCB which I had manufactured and soldered the SMD and through-hole and ICs to that, and treat it as its own standalone signal source. Once I did that, literally every obscure problem I was having disappeared and the downstream counter worked perfectly. When you look at the various waveforms (I added a bunch of test points to the PCB to make this easy) the results of my PCB produces perfect square waves. I found it interesting how many suggested hardware solutions I had to try (simple RC filter did not work) and how many "experts" I had to ignore before I found a simple solution.
- persnickety 2y agoWhat's with the advice about interrupts and undebounced signals? What does it mean that a flip-flop gets confused? What kind of undesired operation could that cause? Because, quite honestly, if connecting directly means occasional transient failures, then having less hardware is a tempting tradeoff on small PCBs.
- kevin_thibedeau 2y agoMy test whenever I get handed someone else's code with a debounce routine is to hammer the buttons with rapid presses, gradually slowing down. That shows if the filter is too aggressive and misses legitimate presses. I also see strange behavior when they're implemented wrong like extra presses that didn't happen or getting stuck thinking the button is still held when it isn't.
- SOLAR_FIELDS 2y agoWhat kind of line of work gives you the ability to discuss debounce routines as an everyday enough occurrence to speak with authority on the matter, if you don’t mind me asking?
- HeyLaughingBoy 2y agoPretty much anything that involves direct conversations with hardware. I build medical devices.
- geerlingguy 2y agoThis is one of the best treatises on debounce, I've read it a number of times and probably will again. One of the best things I've done to help with really bad debounce is spend time testing a number of buttons to find the designs that have, at the hardware/contact level, much less bounce. Some buttons wind up with tens of ms of bounce, and it's hard to correct for it and meet expectations all in software.
- StayTrue 2y agoAgree. Helped me (a software guy) when I needed it. Automatic upvote.
- theamk 2y agoJust don't implement SR debouncer, OK? And don't use MC140* series chips, those don't work with 3.3V used by modern micros. And when he says: > Never run the cap directly to the input on a microprocessor, or to pretty much any I/O device. Few of these have any input hysteresis. that's not true today, most small MCU made in 2005 or later (such as AVR and STM8 series) have input hysteresis, so feel free to connect cap directly to it. And when he says: > don't tie undebounced switches, even if Schmitt Triggered, to interrupt inputs on the CPU that's also not correct for most modern CPUs, they no longer have a dedicated interrupt line, and interrupts share hardware (including synchronizer) with GPIO. So feel free to tie undebounced switch to interrupt lines.
- AdamH12113 2y agoWhat's wrong with the SR latch debouncer?
- theamk 2y agoIt needs SPDT switch, and that rules out most of buttons. And if you do end up choosing SPDT switch, then there are much simpler designs which have switch toggle between Vcc and GND, like Don Lancaster's debouncer [0]. That design is especially useful if you have many switches, as you can wire all VCCs and GNDs in parallel, and use 8-channel buffers to debounce multiple ones. The SR latch schematics only makes sense if you are working with TTL logic (popular in 1970/1980) which did not nave a symmetric drive output pattern, and there is absolutely no reason to use it in 2000's. [0] https://modwiggler.com/forum/viewtopic.php?p=275228&sid=52c0156aa2e26c18d031c0beca50a53e#p275228 https://modwiggler.com/forum/viewtopic.php?p=275228&sid=52c0...
- theamk 2y agoAnalysis is nice, although the graph style is very much 2005. The conclusion is that as long as you don't get a crappy switch, 10mS debounce interval should be sufficient. I would not pay much attention to the rest of the text. The hardware debouncer advice is pretty stale - most of the modern small MCUs have no problem with intermediate levels, nor with high frequency glitches. Schmidt triggers are pretty common, so feel free to ignore the advice and connect cap to MCU input directly. Or skip the cap, and do everything in firmware, MCU will be fine, even with interrupts. (Also, I don't get why the text makes firmware debouncer sound hard? There are some very simple and reliable examples, include the last one in the text which only takes a few lines of code.)
- michaelt 2y ago> Also, I don't get why the text makes firmware debouncer sound hard? The article links to Microchip's PIC12F629 which is presumably the type of chip the author was working with at the time. This would usually have been programmed in assembly language. Your program could be no longer than 1024 instructions, and you only had 64 bytes of RAM available. No floating point support, and if you want to multiply or divide integers? You'll need to do it in software, using up some of your precious 1024 instructions. You could get a C compiler for the chips, but it cost a week's wages - and between the chip's incredibly clunky support for indirect addressing and the fact there were only 64 bytes of RAM, languages that needed a stack came at a high price in size and performance too. And while we PC programmers can just get the time as a 64-bit count of milliseconds and not have to worry about rollovers or whether the time changed while you were in the process of reading it - when you only have an 8-bit microcontroller that was an unimaginable luxury. You'd get an 8-bit clock and a 16-bit clock, and if you needed more than that you'd use interrupt handlers. It's still a neat chip, though - and the entire instruction set could be defined on a single sheet of paper, so although it was assembly language programming it was a lot easier than x86 assembly programming.
- Cumpiler69 2y ago>No floating point support, and if you want to multiply or divide integers? You'll need to do it in software, using up some of your precious 1024 instructions. Very much not true as almost nobody ever used floating point in commercial embedded applications. What you use is fractional fixed point integer math. Used to be working in Automotive EV motor control in the past and even though the MCUs/DSPs we used had floating point HW for a long time now, we still never ued it for safety and code portability reasons. All math was fractional integer. Maybe today's ECUs started using floating point but that was definitely not the case in the past, and every embedded dev wort his salt should be comfortable doing DSP math in without floating point. https://en.wikipedia.org/wiki/Fixed-point_arithmetic https://en.wikipedia.org/wiki/Fixed-point_arithmetic https://en.wikipedia.org/wiki/Q_(number_format) https://en.wikipedia.org/wiki/Q_(number_format)
- khafra 2y ago> One vendor told me reliability simply isn't important as users will subconsciously hit the button again and again till the channel changes. Orthogonally to the point of this excellent article, I found it striking how this was probably true, once--and then TVs got smart enough that it took seconds to change channels, instead of milliseconds. And then it was no longer possible for input failures to be corrected subconsciously.
- somat 2y agonobody cares enough to actually do it. but what would it take to have near instantaneous channel changes again?, prestarting a second stream in the background? And realistically the linear array of channels is also dead so it really does not matter. so I guess the modern equivalent is having a snappy UI. A horrible idea, as if our current tv features were not already bad enough. the modern equivalent to quick channel changes would be a learning model that guesses what you you want to see next, has that stream prestarted then have the "next channel" button tied to activate that stream. The actual reason this is a bad idea, I mean above and beyond the idea that we want learning models in our tv's. Is that the manufactures would very quickly figure out that instead of the agent working for their customers they could sell preferential weights to the highest bidder. closing thought... Oh shit I just reinvent youtube shorts(or perhaps tik tok, but I have managed to avoid that platform so far)... an interface I despise with a passion.
- hulitu 2y ago> so I guess the modern equivalent is having a snappy UI. "With all those DLLs and network access, Dave, you're going to find this rather difficult" /s
- jakewins 2y agoThere was some article from early instagram times about this the other week - that an innovation there was that they started the upload as soon as the picture was taken, so after the user filled out the caption part and hit “submit”, the “upload” was instantaneous
- gosub100 2y ago
- neuroelectron 2y agoI just bought a horrible Lenovo keyboard with terrible debouncing. For some reason, it seems to only affect the vowels... is this sabotage?
- mlvljr 2y agoBy ancient Egyptians?
- bambax 2y ago> Years ago a pal and I installed a system for the Secret Service that had thousands of very expensive switches on panels in a control room. We battled with a unique set of bounce challenges because the uniformed officers were too lazy to stand up and press a button. They tossed rulers at the panels from across the room. Different impacts created quite an array of bouncing. It's impossible to guess how users will use a system until they can be observed in the wild.
- dpkirchner 2y agoThis probably induced a lot of Object Thrown Operation (OTO) once word spread to everyone -- not just the lazy -- that it was possible to activate the buttons from afar.
- matheusmoreira 2y agoWish I had known about this article last year when developers added debouncing to the Sensor Watch project. I had to learn a lot of this from scratch in order to review and merge in their changes. I'm still running their code right now on my watch. It uses timers to allow the switch to settle before triggering input events. Dramatically improved its usability. Latency noticeably increased but without it interfaces which required holding down buttons simply didn't work reliably.
- ghusbands 2y agoDebouncing doesn't need to delay a touchstart event, in general, so latency shouldn't really increase in a carefully designed system, especially if you can be animating in advance of the touchend event.
- ghusbands 2y agoThis is an interesting take on debouncing, but I found the choice of TV remotes as an example a bit confusing. From my understanding, the issues with remote controls aren’t typically caused by bouncing in the mechanical sense but rather by the design of the IR communication. Most remotes transmit commands multiple times per second (e.g., 9–30 times) intentionally, and the receiver handles these signals based on timing choices. If there are problems like double channel jumps or missed commands, it’s more about how the receiver interprets the repeated signals rather than a classic switch debounce issue. There’s definitely a similarity in handling timing and filtering inputs, but it seems like the core issue with remotes is different, as they must already handle repeated commands by design.
- HPsquared 2y agoThen there's the "hold to repeat" mechanic, where if you hold it long enough it'll add virtual presses for you.
- nickcw 2y ago> But some environments are notoriously noisy. Many years ago I put a system using several Z80s and a PDP-11 in a steel mill. A motor the size of a house drawing thousands of amps drove the production line. It reversed direction every few seconds. The noise generated by that changeover coupled everywhere, and destroyed everything electronic unless carefully protected. We optocoupled all cabling simply to keep the smoke inside the ICs, where it belongs. All digital inputs still looked like hash and needed an astonishing amount of debounce and signal conditioning. :-) I had a similar experience with a elevator motor and a terminal. The electronics worked absolutely fine, but when someone operated the elevator it occasionally produced phantom keypresses on the capacitive keypad. This was perhaps understandable, but what really confused the users was that these phantom keypresses sometimes pressed the not fitted debug buttons (which weren't on the production keypad) which stuck the device into debug mode! We learnt not to include the debug code in the production firmware and beefed up the transient suppression hardware and the debouncing firmware to fix.
- HeyLaughingBoy 2y agoMy favorite noise story is from just a couple years ago. Our controller would run fine for hours or days and then reset for no apparent reason. Looking at the debug output, I could tell that it wasn't a watchdog or other internal reset (e.g., system panic) and there had been no user input. The debug log basically said that someone pushed the reset button, which clearly wasn't happening. The EE and I were standing around the machine and he happened to be in front of the UI when it reset and I mentioned that I heard a soft click just before he said that it reset, but we had no hardware in the region where I thought the noise came from. Finally, we put two and two together and realized that the system included a propane heater with an automatic controller and the noise I heard was probably the propane igniter. The high voltage from the igniter was wirelessly coupling into one of the I/O lines going to the controller board. The reason that the problem had suddenly started happening after months of trouble-free development was that the customer had rerouted some of the wiring when they were in the machine fixing something else and moved it closer to the heater. In 30 years of doing this, I can count on one hand the number of times I've had to deal with noise that was coupling in through the air!
- roland35 2y agoI've actually never really had much issue with switch bounces - I think many modern microcontrollers have built in gpio circuits which seems to help with this.
- the__alchemist 2y agoI've been using the perhaps-too-simple: - Button triggers interrupt - Interrupt starts a timer - Next time interrupt fires, take no action if the timer is running. (Or use a state variable of some sort) Of note, this won't work well if the bounce interval is close to the expected actuation speed, or if the timeout interval isn't near this region.
- knodi123 2y ago> this won't work well if the bounce interval is close to the expected actuation speed lol, or you could do what my TV does- say "to hell with user experience" and use an interrupt timer anyway. If I hold down my volume-up button (The physical one on the TV!), I get a quick and fluid increase. But if I hammer the button 4 times per second, the volume still only goes up 1 ticke per second.
- nomel 2y agoLoosely related, my HiSense TV has a wifi remote that apparently sends separate key up and down events to the TV. If the wifi happens to go down while you're holding the volume up button, it never sees the "key up" so will just hold whatever button indefinitely, including the volume button, which is how I discovered it.
- nomel 2y agoThis is functionally identical to the capacitive approach. Pressing the button charges the cap whose voltage decays when released (starts the timer). If the button is pressed before it decays below the "release" threshold (timer expires), the cap is recharged (timer restarted).
- seoulbigchris 2y agoI've used that article several times in the past. I'll also note that many years ago, on projects which were not cost sensitive, we would often use the MC14490 IC for hardware debouncing (mentioned in part 2 of this article).
- Certified 2y agoI'm a big fan of debouncing in hardware with the MAX3218 chip. It will debounce by waiting 40ms for the signal to "settle" before passing it on. This saves your microprocessor interrupts for other things. It also will work with 12 or 24 volt inputs and happily output 3.3 or 5v logic to the microprocessor. It is pricey though at $6-10 each.
- the__alchemist 2y agoMy thought is: This introduces latency that is not required (40ms could be a lot IMO depending on the use.) It's not required because you don't need latency on the first high/low signal; you only need to block subsequent ones in the bounce period; no reason to add latency to the initial push. Also, (Again, depends on the use), there is a good chance you're handling button pushes using interrupts regardless of debouncing.
- Certified 2y agoI guess I should rephrase. It saves all the interrupts except the one triggered at 40ms delay. For every button press without hardware debouncing, you can have 10s - 100s of 1to0 and 0to1 transitions on the microcontroller pin. This is easily verified on a oscope, even with "good" $50+ honeywell limit switches. Every single one of those transitions triggers an interrupt and robs cpu cycles from other things the microprocessor is doing. The code in the interrupt gets more complex because now it has to do flag checks and use timers (bit bashing) every time they are triggered instead of just doing the action the button is supposed to trigger. None of this is to say one way is the "right" or "wrong" way to do it, but putting the hardware debouncing complexity into hardware specifically designed to handling it, and focusing on the problem I am actually trying to solve in firmware is my personal preferred way of doing it.
- theamk 2y agothat seems like a real overkill - it's a full-blown RS232 receiver _and_ transmitter, including two DC-DC converters (with inductor and capacitor) that you don't even use... Also, "R_IN absolute max voltage" is +/- 25V, so I really would not use this in 24V system. If you want slow and reliable input for industrial automation, it seems much safer to make one yourself - an input resistor, hefty diode/zener, voltage divider, maybe a schmitt trigger/debouncer made from opamp if you want to get real fancy.
- JimmyWilliams1 2y ago[dead]
- slippy 2y agoI read through a whole page, wondering when we are getting to legal stuff, before I went back and re-read the title. "Contact" not "Contract"....
- cushychicken 2y agoBe sure to read Jack’s mega treatise on low power hardware/software design if you haven’t yet. https://www.ganssle.com/reports/ultra-low-power-design.html https://www.ganssle.com/reports/ultra-low-power-design.html One of the best practical EE essays I’ve ever read, and a masterwork on designing battery powered devices.
- denimnerd42 2y agothe evoluent vertical mouse I use has a notorious short lifespan because the switches aren't debounced or aren't debounced for a long enough period after only a year or two of wear. i demonstrated on an arduino that additional debouncing logic could fix the issue transparently to the user but never went further than that.