Button debouncing by using Ticker interrupts
Dependencies: mbed
Diff: main.cpp
- Revision:
- 0:a8167a8804f5
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Thu Jan 07 14:03:12 2016 +0000 @@ -0,0 +1,36 @@ +/** 08_button_debouncer + * + * Switches a LED on/off by pushbutton. + * The state of the button is sampled by a Ticker timer + * in each 20 ms and thus the button is debounced. + * This program can be regarded as an improved version + * of 07_button_interrupt program. + * + * Hardware requirements: + * - FRDM-KL25Z board + * - Pusbutton (tied between D3 and GND) + */ + +#include "mbed.h" + +DigitalIn button(D3,PullUp); // Pusbutton input +DigitalOut led(LED_BLUE); // LED output (the blue LED) +Ticker sampler; // Ticker for button state sampling +volatile uint8_t button_state = 1; // Initially released + +void button_check() +{ + button_state = (button_state<<1) | (button & 1); // shift in button state + if((button_state & 3)==2) { // Check for H -> L transition + led = !led; // Switch LED state + } +} + +int main() +{ + led = 1; // LED off + sampler.attach(&button_check,0.02); // sample button state in each 20 ms + while (true) { + wait(1); // do nothing + } +} \ No newline at end of file