Pushbutton counter demo showing switch contact bounce

Dependencies:   mbed

main.cpp

Committer:
4180_1
Date:
2011-09-20
Revision:
0:996a0fc1fdea

File content as of revision 0:996a0fc1fdea:

#include "mbed.h"

DigitalOut myled(LED1);
DigitalOut myled2(LED2);
DigitalOut myled3(LED3);
DigitalOut myled4(LED4);

DigitalIn pb(p8);
// SPST Pushbutton count demo using internal PullUp function
// no external PullUp resistor needed
// Pushbutton from P8 to GND.
// Demonstrates need for debounce - will sometimes count more than once per button hit
// This occurs on all switches due to mechanical contact bounce
int main()
{ 
int count=0;
int old_pb=1;
int new_pb;
    // Use internal pullup for pushbutton
    pb.mode(PullUp);
    // Delay for initial pullup to take effect
    wait(.001);
    while(1) {
        new_pb = pb;
        if ((new_pb==0) && (old_pb==1)) count++;
        myled4 = count & 0x01;
        myled3 = (count & 0x02)>>1;
        myled2 = (count & 0x04)>>2;
        myled = (count & 0x08)>>3;
        old_pb = new_pb;
    }
}