Pushbutton counter demo showing switch contact bounce

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 
00003 DigitalOut myled(LED1);
00004 DigitalOut myled2(LED2);
00005 DigitalOut myled3(LED3);
00006 DigitalOut myled4(LED4);
00007 
00008 DigitalIn pb(p8);
00009 // SPST Pushbutton count demo using internal PullUp function
00010 // no external PullUp resistor needed
00011 // Pushbutton from P8 to GND.
00012 // Demonstrates need for debounce - will sometimes count more than once per button hit
00013 // This occurs on all switches due to mechanical contact bounce
00014 int main()
00015 { 
00016 int count=0;
00017 int old_pb=1;
00018 int new_pb;
00019     // Use internal pullup for pushbutton
00020     pb.mode(PullUp);
00021     // Delay for initial pullup to take effect
00022     wait(.001);
00023     while(1) {
00024         new_pb = pb;
00025         if ((new_pb==0) && (old_pb==1)) count++;
00026         myled4 = count & 0x01;
00027         myled3 = (count & 0x02)>>1;
00028         myled2 = (count & 0x04)>>2;
00029         myled = (count & 0x08)>>3;
00030         old_pb = new_pb;
00031     }
00032 }