program: POLLING

main.cpp

Committer:
alifsohen
Date:
2020-09-18
Revision:
1:1ce199c334c2
Parent:
0:f1c27b98a650

File content as of revision 1:1ce199c334c2:

#include "mbed.h"
 
// Sample answer for lab 2
// -----------------------
//   Poll button
//   Vary period of flashing LED

DigitalIn button(PTD0, PullUp);
DigitalOut led(LED_RED);

Thread pollT ; // thread to poll
Thread flashT ; // thread to flash light
volatile int event = 0 ;

enum switchPos { up, down, bounce };
void polling() {
    switchPos pos = up ;
    int bcounter = 0 ;
    while (true) {
        switch (pos) {
            case up :
                if (button == 1) {
                    event = 1 ;  // transition occurred
                    pos = down ;
                }
                break ;
            case down : 
                if (button == 0) {
                    bcounter = 3 ; // wait four cycles
                    pos = bounce ;
                }
                break ;
            case bounce :
                if (button == 1) { // button has bounced
                    pos = down ;     // no event
                } else if (bcounter == 0) {
                    pos = up ;
                } else {
                    bcounter-- ;
                }
                break ;
        }
        ThisThread::sleep_for(100) ; // delay for 100ms 
    }
}

// Main thread
//   Start polling thread
//   Flash light with a period that varies with each button press 
int main()
{
    pollT.start(&polling) ; // start the polling thread running 
    int delay = 1 ; // range 1, 2, 3, 4, 5
    int counter = 0 ; // counter for cycles since last flash
    while(true) {
        counter++ ; // increment the counter
        if (event) {
            delay = (delay % 5) + 1 ;
            event = 0 ; // clear the event
        }
        if (counter >= 2 * delay) { // 2, 4, 6, 8, 10
            led = !led ;
            counter = 0 ;
        }
        ThisThread::sleep_for(100) ; // delay for 100ms 
    }


}