lab 2 part 1

main.cpp

Committer:
anair12345
Date:
2019-02-07
Revision:
4:cfd889aca1e1
Parent:
3:8d87cbabe37e

File content as of revision 4:cfd889aca1e1:

#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
//int noofcycles = 1 ; 
//int waittime = 0.1 ;

int waittime [5] = { 2,4,6,8,10 };
enum buttonPos { up, down, bounce }; // Button positions
void polling() {
    buttonPos pos = up ;
    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 ;
        }
        wait(0.03);
    }
}

/*  ---- Main function (default thread) ----
    Note that if this thread completes, nothing else works
 */
int main() {
    led = 1 ;  // Initially off
    pollT.start(callback(polling));
    int i = 0 ;
    int count = waittime[i];
    while(true) {
        wait(0.1);
        if (pressEvent) {
            pressEvent = 0 ; // clear the event variable
            i = (i+1)%5;
            count = waittime[i];
        }
        else{
            if(count!=0){
                count-- ; 
            }
            else if(count == 0){
               led = !led ; 
               count = waittime[i];        
            }
        }        
        
    }
}