The ButtonHandler is a button observer: it reacts when a button is pressed.
In particular when the ButtonHandler is trigger it calls a callback function (that is passed to its constructor) which is defined as:
using ButtonCallback = std::function<void(uint8_t, ButtonPress)>;
where the two parameters are a button ID and the ButtonPress value according to the amount of time it has been pressed. The possible values that ButtonPress can assume are:
enum class ButtonPress
{
DOWN, // As soon as the button is pressed
UP, // When the button is released
SHORT, // After a short press
LONG, // After a long press
VERY_LONG // After a very long press
};
As an example if we press the button for a long time, the callback will be called one time with a ButtonPress paramenter equal to DOWN
, one time with LONG
and one time with UP
.
The ButtonHandler class also exposes a method to check if the button is currently being pressed or not:
static bool isPressed() { return Button::value(); }
Finally consider that the GPIO associated to the button has to be passed as a template argument when instantiating the ButtonHandler object.
You can find the complete implementation of the ButtonHandler in src/shared/utils/ButtonHandler.h
.
Example
This example shows the usage of the ButtonHandler, using the STM32F407VG on-board user button, which is connected to pin PA0
.
First of all import the dependencies. Then define the GPIO PA0
and an ID for the button.
#include <Common.h>
#include "utils/ButtonHandler.h"
using namespace miosix;
typedef Gpio<GPIOA_BASE, 0> button;
const uint8_t button_id = 1;
Then we also have to define a callback:
void buttonCallback(uint8_t btn_id, ButtonPress btn_press)
{
TRACE("Callback! btn_id=%d, btn_press=%d \n", btn_id, btn_press);
}
This function is called every time the ButtonHandler is triggered. The buttonCallback
will be called multiple times, first when the button is pressed (btn_press
will be equal to DOWN
) and then when it is released, passing a different value to btn_press
according to amount of time the button has been kept pressed. When we release it, the callback is also called with UP
as a paramater.
In the main we can create a ButtonHandler passing the above defined GPIO, button ID and callback and start it:
int main()
{
ButtonHandler<button> bh(button_id, &buttonCallback);
bh.start();
while (1)
{
// do stuff
}
return 0;
}
Output
If we press the button for a long time, the expected output is:
0.92> Callback! btn_id=1, btn_press=0 # btn_press=DOWN, as soon as the button is pressed
1.94> Button pressed (long) (10 ticks).
1.96> Callback! btn_id=1, btn_press=3 # btn_press=LONG, after a long time when the button is released
1.98> Callback! btn_id=1, btn_press=1 # btn_press=UP, when the button is released