Alif Ahmed / Mbed OS digitalInPolling_sample_program
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);
00012 DigitalOut led(LED1);
00013 
00014 Thread pollT ; // thread to poll
00015 volatile int pressEvent = 0 ;  // Variabe set by the polling thread
00016   // Sharing a global variable between two threads is not safe in general
00017   //  but it can be ok if a) update is atomic and b) only one thread writes
00018 
00019 enum buttonPos { up, down, bounce }; // Button positions
00020 void polling() {
00021     buttonPos pos = up ;
00022     int bcounter = 0 ;
00023     while (true) {
00024         ThisThread::sleep_for(30) ; // poll every 30ms
00025         switch (pos) {
00026             case up :
00027                 if (!b1.read()) {    // now down 
00028                     pressEvent = 1 ;  // transition occurred
00029                     pos = down ;
00030                 }
00031                 break ;
00032             case down : 
00033                 if (b1 == 1) { // no longer down
00034                     bcounter = 3 ; // wait four cycles
00035                     pos = bounce ;
00036                 }
00037                 break ;
00038             case bounce :
00039                 if (b1 == 0) { // down again - button has bounced
00040                     pos = down ;   // no event
00041                 } else if (bcounter == 0) {
00042                     pos = up ;     // delay passed - reset to up
00043                 } else {
00044                     bcounter-- ;   // continue waiting
00045                 }
00046                 break ;
00047         }
00048     }
00049 }
00050 
00051 /*  ---- Main function (default thread) ----
00052     Note that if this thread completes, nothing else works
00053  */
00054 int main() {
00055     led = 1 ;  // Initially off
00056     pollT.start(callback(polling));
00057 
00058     while(true) {
00059         if (pressEvent) {
00060             pressEvent = 0 ; // clear the event variable
00061             led = !led ;
00062         }
00063         ThisThread::sleep_for(100) ; // delay for 100ms 
00064     }
00065 }