Skip to main content

Chapter 2 Digital Inputs: Switches and Debouncing

The goal of this chapter is to read a pushbutton switch reliably with the STM32C031C6, so that one press of a finger produces exactly one response from the program. A pin configured as an input is either HIGH or LOW, so reading a button looks as though it should take one line of code. It takes more than that, for two reasons. The first is that a button by itself does not produce a 1 or a 0: it only closes a connection from the pin to ground, and a pin with nothing driving it reads unpredictably. The second is that mechanical switches bounce: the contacts chatter for a few milliseconds every time you press or release them, generating dozens of spurious transitions.
This chapter covers three class days. We’ll configure a GPIO (general-purpose input/output) pin as an input with an internal pull-up resistor and read it in a polling loop. We’ll then learn to use the Analog Discovery 2 oscilloscope and put it on the button to see the bounce. We’ll then get rid of the bounce, in hardware with a capacitor and in software by waiting it out. That still leaves a second problem, which is that polling reports the button’s level when what a toggle needs is the moment it changes, and the pattern that solves it is the state machine.