S. Marsanne

Simple Keyboard Sample Code

Discussion created by S. Marsanne Employee on Dec 18, 2016

Most devices have keyboards, being implemented as Analog (see ADCs overview), Triangular, Matrixed, Digital, Capacitive, etc...


Here is a piece of code that has been used over the years on STM8 or STM32 which tries to cover most of the applications needs.


When a key is pressed:


To avoid glitches and false positive, a debouncing (double check) must be implemented

Then a key pressed event can be reported.


After some time, while keeping the key pressed, you'd like to simulate a key press repeatly event with some certain repetition frequency which increases after a while. (this happens when trying to increase the seconds of a clock from 0 to 59 manually)


Also, many devices, including smart phones, have special key behaviour when a key is maintained for a long time (3 to 5 seconds that some people call "hot key"), for example to go to service menu, or to workaround that there are less keys than needed.


Usually, the keys are scanned at periodic times in a main loop, say every 50+ msec, then GUI (graphical user interface) will get key status right after key scan.


Here is an example of keyboard scan sample code for analog or digital (one pin, one GPIO) keyboards.

For each GPIO, we need to count how long a key is pressed and update status.


The schematics of boards is for reference using STM32F437 and another one using STM8L151