Mejora la lectura de un pulsador disminuyendo el debounce que se genera al precionarlo.

Dependencies:   mbed

Committer:
CCastrop1012
Date:
Fri Sep 03 04:46:20 2021 +0000
Revision:
0:1220be6b963d
Mejora la lectura de un pulsador disminuyendo el debounce que se genera al precionarlo.

Who changed what in which revision?

UserRevisionLine numberNew contents of line
CCastrop1012 0:1220be6b963d 1 #include "mbed.h"
CCastrop1012 0:1220be6b963d 2
CCastrop1012 0:1220be6b963d 3 DigitalOut led1(LED1);
CCastrop1012 0:1220be6b963d 4
CCastrop1012 0:1220be6b963d 5 InterruptIn button1(USER_BUTTON);
CCastrop1012 0:1220be6b963d 6 volatile bool button1_pressed = false; // Used in the main loop
CCastrop1012 0:1220be6b963d 7 volatile bool button1_enabled = true; // Used for debouncing
CCastrop1012 0:1220be6b963d 8 Timeout button1_timeout; // Used for debouncing
CCastrop1012 0:1220be6b963d 9
CCastrop1012 0:1220be6b963d 10 // Enables button when bouncing is over
CCastrop1012 0:1220be6b963d 11 void button1_enabled_cb(void)
CCastrop1012 0:1220be6b963d 12 {
CCastrop1012 0:1220be6b963d 13 button1_enabled = true;
CCastrop1012 0:1220be6b963d 14 }
CCastrop1012 0:1220be6b963d 15
CCastrop1012 0:1220be6b963d 16 // ISR handling button pressed event
CCastrop1012 0:1220be6b963d 17 void button1_onpressed_cb(void)
CCastrop1012 0:1220be6b963d 18 {
CCastrop1012 0:1220be6b963d 19 if (button1_enabled) { // Disabled while the button is bouncing
CCastrop1012 0:1220be6b963d 20 button1_enabled = false;
CCastrop1012 0:1220be6b963d 21 button1_pressed = true; // To be read by the main loop
CCastrop1012 0:1220be6b963d 22 button1_timeout.attach(callback(button1_enabled_cb), 0.3); // Debounce time 300 ms
CCastrop1012 0:1220be6b963d 23 }
CCastrop1012 0:1220be6b963d 24 }
CCastrop1012 0:1220be6b963d 25
CCastrop1012 0:1220be6b963d 26 int main()
CCastrop1012 0:1220be6b963d 27 {
CCastrop1012 0:1220be6b963d 28 //button1.mode(PullUp); // Activate pull-up
CCastrop1012 0:1220be6b963d 29 button1.fall(callback(button1_onpressed_cb)); // Attach ISR to handle button press event
CCastrop1012 0:1220be6b963d 30
CCastrop1012 0:1220be6b963d 31 int idx = 0; // Just for printf below
CCastrop1012 0:1220be6b963d 32
CCastrop1012 0:1220be6b963d 33 while(1) {
CCastrop1012 0:1220be6b963d 34 if (button1_pressed) { // Set when button is pressed
CCastrop1012 0:1220be6b963d 35 button1_pressed = false;
CCastrop1012 0:1220be6b963d 36 printf("Button pressed %d\n", idx++);
CCastrop1012 0:1220be6b963d 37 led1 = !led1;
CCastrop1012 0:1220be6b963d 38 }
CCastrop1012 0:1220be6b963d 39 }
CCastrop1012 0:1220be6b963d 40 }