Pushbutton counter demo with debounce and a callback using interrupts

Dependencies:   PinDetect mbed

Committer:
4180_1
Date:
Tue Sep 20 14:06:28 2011 +0000
Revision:
0:cc87c48aa43c

        

Who changed what in which revision?

UserRevisionLine numberNew contents of line
4180_1 0:cc87c48aa43c 1 #include "mbed.h"
4180_1 0:cc87c48aa43c 2 #include "PinDetect.h"
4180_1 0:cc87c48aa43c 3 // must import Cookbook PinDetct library into project
4180_1 0:cc87c48aa43c 4 // URL: http://mbed.org/users/AjK/libraries/PinDetect/lkyxpw
4180_1 0:cc87c48aa43c 5
4180_1 0:cc87c48aa43c 6 DigitalOut myled(LED1);
4180_1 0:cc87c48aa43c 7 DigitalOut myled2(LED2);
4180_1 0:cc87c48aa43c 8 DigitalOut myled3(LED3);
4180_1 0:cc87c48aa43c 9 DigitalOut myled4(LED4);
4180_1 0:cc87c48aa43c 10
4180_1 0:cc87c48aa43c 11 PinDetect pb(p8);
4180_1 0:cc87c48aa43c 12 // SPST Pushbutton debounced count demo using interrupts and callback
4180_1 0:cc87c48aa43c 13 // no external PullUp resistor needed
4180_1 0:cc87c48aa43c 14 // Pushbutton from P8 to GND.
4180_1 0:cc87c48aa43c 15 // A pb hit generates an interrupt and activates the callback function
4180_1 0:cc87c48aa43c 16 // after the switch is debounced
4180_1 0:cc87c48aa43c 17
4180_1 0:cc87c48aa43c 18 // Global count variable
4180_1 0:cc87c48aa43c 19 int volatile count=0;
4180_1 0:cc87c48aa43c 20
4180_1 0:cc87c48aa43c 21 // Callback routine is interrupt activated by a debounced pb hit
4180_1 0:cc87c48aa43c 22 void pb_hit_callback (void) {
4180_1 0:cc87c48aa43c 23 count++;
4180_1 0:cc87c48aa43c 24 myled4 = count & 0x01;
4180_1 0:cc87c48aa43c 25 myled3 = (count & 0x02)>>1;
4180_1 0:cc87c48aa43c 26 myled2 = (count & 0x04)>>2;
4180_1 0:cc87c48aa43c 27 }
4180_1 0:cc87c48aa43c 28 int main() {
4180_1 0:cc87c48aa43c 29
4180_1 0:cc87c48aa43c 30 // Use internal pullup for pushbutton
4180_1 0:cc87c48aa43c 31 pb.mode(PullUp);
4180_1 0:cc87c48aa43c 32 // Delay for initial pullup to take effect
4180_1 0:cc87c48aa43c 33 wait(.01);
4180_1 0:cc87c48aa43c 34 // Setup Interrupt callback function for a pb hit
4180_1 0:cc87c48aa43c 35 pb.attach_deasserted(&pb_hit_callback);
4180_1 0:cc87c48aa43c 36 // Start sampling pb input using interrupts
4180_1 0:cc87c48aa43c 37 pb.setSampleFrequency();
4180_1 0:cc87c48aa43c 38
4180_1 0:cc87c48aa43c 39 //Blink myled in main routine forever while responding to pb changes
4180_1 0:cc87c48aa43c 40 // via interrupts that activate the callback counter function
4180_1 0:cc87c48aa43c 41 while (1) {
4180_1 0:cc87c48aa43c 42 myled = !myled;
4180_1 0:cc87c48aa43c 43 wait(.5);
4180_1 0:cc87c48aa43c 44 }
4180_1 0:cc87c48aa43c 45
4180_1 0:cc87c48aa43c 46 }