Pushbutton counter demo showing switch contact bounce

Dependencies:   mbed

Committer:
4180_1
Date:
Tue Sep 20 13:59:06 2011 +0000
Revision:
0:996a0fc1fdea

        

Who changed what in which revision?

UserRevisionLine numberNew contents of line
4180_1 0:996a0fc1fdea 1 #include "mbed.h"
4180_1 0:996a0fc1fdea 2
4180_1 0:996a0fc1fdea 3 DigitalOut myled(LED1);
4180_1 0:996a0fc1fdea 4 DigitalOut myled2(LED2);
4180_1 0:996a0fc1fdea 5 DigitalOut myled3(LED3);
4180_1 0:996a0fc1fdea 6 DigitalOut myled4(LED4);
4180_1 0:996a0fc1fdea 7
4180_1 0:996a0fc1fdea 8 DigitalIn pb(p8);
4180_1 0:996a0fc1fdea 9 // SPST Pushbutton count demo using internal PullUp function
4180_1 0:996a0fc1fdea 10 // no external PullUp resistor needed
4180_1 0:996a0fc1fdea 11 // Pushbutton from P8 to GND.
4180_1 0:996a0fc1fdea 12 // Demonstrates need for debounce - will sometimes count more than once per button hit
4180_1 0:996a0fc1fdea 13 // This occurs on all switches due to mechanical contact bounce
4180_1 0:996a0fc1fdea 14 int main()
4180_1 0:996a0fc1fdea 15 {
4180_1 0:996a0fc1fdea 16 int count=0;
4180_1 0:996a0fc1fdea 17 int old_pb=1;
4180_1 0:996a0fc1fdea 18 int new_pb;
4180_1 0:996a0fc1fdea 19 // Use internal pullup for pushbutton
4180_1 0:996a0fc1fdea 20 pb.mode(PullUp);
4180_1 0:996a0fc1fdea 21 // Delay for initial pullup to take effect
4180_1 0:996a0fc1fdea 22 wait(.001);
4180_1 0:996a0fc1fdea 23 while(1) {
4180_1 0:996a0fc1fdea 24 new_pb = pb;
4180_1 0:996a0fc1fdea 25 if ((new_pb==0) && (old_pb==1)) count++;
4180_1 0:996a0fc1fdea 26 myled4 = count & 0x01;
4180_1 0:996a0fc1fdea 27 myled3 = (count & 0x02)>>1;
4180_1 0:996a0fc1fdea 28 myled2 = (count & 0x04)>>2;
4180_1 0:996a0fc1fdea 29 myled = (count & 0x08)>>3;
4180_1 0:996a0fc1fdea 30 old_pb = new_pb;
4180_1 0:996a0fc1fdea 31 }
4180_1 0:996a0fc1fdea 32 }