Debounce and latch a button input

Dependencies:   mbed

Committer:
ethanharstad
Date:
Mon Jun 02 06:47:09 2014 +0000
Revision:
0:59aa41d04f51
Initial commit

Who changed what in which revision?

UserRevisionLine numberNew contents of line
ethanharstad 0:59aa41d04f51 1 #include "mbed.h"
ethanharstad 0:59aa41d04f51 2
ethanharstad 0:59aa41d04f51 3 Serial pc(USBTX, USBRX);
ethanharstad 0:59aa41d04f51 4 DigitalIn btn(USER_BUTTON);
ethanharstad 0:59aa41d04f51 5 DigitalOut led(LED1);
ethanharstad 0:59aa41d04f51 6 Timer timer;
ethanharstad 0:59aa41d04f51 7 Timer debounce;
ethanharstad 0:59aa41d04f51 8
ethanharstad 0:59aa41d04f51 9 bool state = false;
ethanharstad 0:59aa41d04f51 10 bool prevState = false;
ethanharstad 0:59aa41d04f51 11 bool counting = false;
ethanharstad 0:59aa41d04f51 12
ethanharstad 0:59aa41d04f51 13 int main() {
ethanharstad 0:59aa41d04f51 14 while(true) {
ethanharstad 0:59aa41d04f51 15 state = btn;
ethanharstad 0:59aa41d04f51 16 if(state != prevState) {
ethanharstad 0:59aa41d04f51 17 debounce.start();
ethanharstad 0:59aa41d04f51 18 }
ethanharstad 0:59aa41d04f51 19 if(debounce.read_ms() > 20) {
ethanharstad 0:59aa41d04f51 20 debounce.stop();
ethanharstad 0:59aa41d04f51 21 debounce.reset();
ethanharstad 0:59aa41d04f51 22 if(!state) {
ethanharstad 0:59aa41d04f51 23 if(!counting) {
ethanharstad 0:59aa41d04f51 24 counting = true;
ethanharstad 0:59aa41d04f51 25 led = true;
ethanharstad 0:59aa41d04f51 26 timer.start();
ethanharstad 0:59aa41d04f51 27 } else {
ethanharstad 0:59aa41d04f51 28 counting = false;
ethanharstad 0:59aa41d04f51 29 led = false;
ethanharstad 0:59aa41d04f51 30 timer.stop();
ethanharstad 0:59aa41d04f51 31 pc.printf("%i ms\n", timer.read_ms());
ethanharstad 0:59aa41d04f51 32 timer.reset();
ethanharstad 0:59aa41d04f51 33 }
ethanharstad 0:59aa41d04f51 34 }
ethanharstad 0:59aa41d04f51 35 }
ethanharstad 0:59aa41d04f51 36 prevState = state;
ethanharstad 0:59aa41d04f51 37 }
ethanharstad 0:59aa41d04f51 38 }