Debounce button by sampling the digital input in each 20 ms. We use a Ticker object and a callback function for this.

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 
00003 DigitalIn button(BUTTON1,PullUp);       // Pusbutton input
00004 DigitalOut led(LED1);                   // Builtin LED
00005 Ticker sampler;                         // Ticker for button state sampling
00006 volatile uint8_t button_state = 1;      // Initially released
00007 
00008 void button_check()
00009 {
00010     button_state = (button_state<<1) | (button & 1); // shift in button state
00011     if((button_state & 3)==2) {         // Check for H -> L transition
00012         led = !led;                     // Switch LED state
00013     }
00014 }
00015 
00016 int main()
00017 {
00018     led = 0;                            // LED off
00019     sampler.attach(&button_check,0.02); // sample button state in each 20 ms
00020     while (true) {
00021         wait(1);                        // do nothing
00022     }
00023 }