Lab 2 Part 2 - Polling Modified

Fork of digitalInPolling_sample by William Marsh

main.cpp

Committer:
diviavad
Date:
2018-02-02
Revision:
3:446895514289
Parent:
2:cd1fe8c29793

File content as of revision 3:446895514289:

#include "mbed.h"

// Labs 2: Example program for polling an input
// --------------------------------------------
// The program uses a thread to poll a digital input
//   - The thread monitors the position of the button
//   - When the button transitions up and down, a press event is signaled 
//   - Button bounce is guarded against
// A second thread (the default one) checks for the press event and toggles the LED

DigitalIn b1(PTD0, PullUp);
DigitalOut led(LED1);

Thread pollT ; // thread to poll
volatile int pressEvent = 0 ;  // Variabe set by the polling thread

enum buttonPos { up, down, bounce }; // Button positions
void polling() {
    buttonPos pos = up ;//chose positing in enum
    int bcounter = 0 ;
    while (true) {
        switch (pos) {
            case up :
                if (!b1.read()) {    // now down 
                    pressEvent = 1 ;  // transition occurred
                    pos = down ;
                }
                break ;
            case down : 
                if (b1 == 1) { // no longer down
                    bcounter = 3 ; // wait four cycles
                    pos = bounce ;
                }
                break ;
            case bounce :
                if (b1 == 0) { // down again - button has bounced
                    pos = down ;   // no event
                } else if (bcounter == 0) {
                    pos = up ;     // delay passed - reset to up
                } else {
                    bcounter-- ;   // continue waiting
                }
                break ;
        }
        Thread::wait(30);
    }
}

/*  ---- Main function (default thread) ----
    Note that if this thread completes, nothing else works
 */
int main() {
      // Initially off
    int wait_time= 200;
    pollT.start(callback(polling));//start thread to check button
    int counter=1;
    while(true) {
        led = !led;
        if (pressEvent) {
            if (counter==2){
                wait_time=400;
                }
            else if(counter==3){
                wait_time=600;
                }
            else if(counter==4){
                wait_time=800;
                }
            else if(counter==5){
                wait_time=1000;
                counter=0;
                }
  
            pressEvent = 0 ; // clear the event variable
            led =!led ;//LED ON
          
            
            counter++;
        }
        Thread::wait(wait_time);
    }
}