How to Handle Switch Debouncing in a Microcontroller Circuit in Embedded C

STM32F407G discovery board

In this article, we go over how to handle switch debouncing in a microcontroller circuit in embedded C.

Switch debouncing in a phenomenon in which a switch is pressed and electrical contact is made by the switch (or button) to underlying circuitry.

Due to the nature of the contact, it may not be a clean press that creates a single electrical contact. It may debouncing, creating a series of presses that could press a switch (or button) several times, creating unintended effects, such as multiple key presses when only one was desired.

So how can we offset or counter these unintended debouncing effects?

Even though this can be offset, at least somewhat, by hardware by placing circuitry such as capacitors by the switch, the approach we take in this article is through software.

This is the theory behind it.

After a switch is pressed, it will make electrical contact with underlying hardware, which shows it was pressed. This may generate debouncing, which creates multiple electrical contact signals. This, again, may create the unintended effects of multiple presses.

So what we need to do is after we detect a switch or button press to register this press and then immediately afterwards add a delay in our software code so that no other presses are detected within this time frame.

This time frame may be about 200ms or 1/5th of a second. This will block any other switch, button, or key press from being registered in this time frame.

You should test out your circuit with the delay you implement and see if this produces a smooth, real-world experience. If not, adjust until you have a good user experience with your input for your circuit.

So by adding a delay in software after a switch press is register avoids multiple presses within that time of delay.

Below is a keypad, which generates key presses.

4x4 keypad

As an example, let's say that we have the following circuit below with an STM32F407G discovery board with this keypad connected to it.

4x4 keypad circuit with an STM32F407G discovery board

After each if statement which searches to see which key is pressed, we add a delay in software which prevents multiple presses in about a 200ms time frame. This offsets against any debouncing that may occur.

You can see this in the code below.

So you can see delays after each if statement, so that we can effectively handle debouncing with a software approach and do not have to be dependent on hardware.

Through a simple delay function, we can counter debouncing that occurs after a switch press.

And this is how to handle switch debouncing in a microcontroller circuit in embedded C.

Related Resources

How to Set Bits of a Number in C

How to Clear Bits of a Number in C

HTML Comment Box is loading comments...