lab2-part1

Fork of digitalInPolling_sample by William Marsh

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 
00003 // Labs 2: Example program for polling an input
00004 // --------------------------------------------
00005 // The program uses a thread to poll a digital input
00006 //   - The thread monitors the position of the button
00007 //   - When the button transitions up and down, a press event is signaled 
00008 //   - Button bounce is guarded against
00009 // A second thread (the default one) checks for the press event and toggles the LED
00010 
00011 DigitalIn b1(PTD0, PullUp);//change the address
00012 DigitalOut led(LED1);
00013 
00014 Thread pollT ; // thread to poll
00015 volatile int pressEvent = 0 ;  // Variabe set by the polling thread
00016 
00017 enum buttonPos { up, down, bounce }; // Button positions
00018 void polling() {
00019     buttonPos pos = up ;
00020     int bcounter = 0 ;
00021     while (true) {
00022         switch (pos) {
00023             case up :
00024                 if (!b1.read()) {    // now down 
00025                     pressEvent = 1 ;  // transition occurred
00026                     pos = down ;
00027                 }
00028                 break ;
00029             case down : 
00030                 if (b1 == 1) { // no longer down
00031                     bcounter = 3 ; // wait four cycles
00032                     pos = bounce ;
00033                 }
00034                 break ;
00035             case bounce :
00036                 if (b1 == 0) { // down again - button has bounced
00037                     pos = down ;   // no event
00038                 } else if (bcounter == 0) {
00039                     pos = up ;     // delay passed - reset to up
00040                 } else {
00041                     bcounter-- ;   // continue waiting
00042                 }
00043                 break ;
00044         }
00045         Thread::wait(30);
00046     }
00047 }
00048 
00049 /*  ---- Main function (default thread) ----
00050     Note that if this thread completes, nothing else works
00051  */
00052 int main() 
00053 {
00054     int speed = 1;    
00055     led = 1 ; 
00056     pollT.start(callback(polling));
00057 
00058     while(true) 
00059     {
00060         if (pressEvent)
00061         { 
00062             speed++;
00063             
00064             if (speed >= 5)
00065                 speed = 1;
00066             
00067             pressEvent = 0;
00068         } 
00069         led = !led ;
00070         Thread::wait(200*speed);
00071     }
00072 }