University of Plymouth - Stages 1, 2 and 3 / Mbed OS Task326

Fork of Task326 by Nicholas Outram

main.cpp

Committer:
noutram
Date:
2019-09-12
Revision:
2:a5a574cd9474
Parent:
0:57de85b71119

File content as of revision 2:a5a574cd9474:

#include "mbed.h"

#ifdef TARGET_NUCLEO_F429ZI
//Uncomment the following line to use onboard LEDs and Switch (F429ZI only)
//#define USEONBOARD
#endif

//A slight improvement - however, the pressing of the switch still registers
//spurious falling edges!

void sw1TimeOutHandler();
void sw1FallingEdge();


#define EDGE_RISEN 1
#define EDGE_FALLEN 0

//Global Objects
#ifdef USEONBOARD
DigitalOut  red_led(LED3);
DigitalOut  green_led(LED1);
InterruptIn   sw1(USER_BUTTON);
#else
DigitalOut  red_led(D7);
DigitalOut  green_led(D5);
InterruptIn   sw1(D4);
#endif

Timeout sw1TimeOut;             //Used to prevent switch bounce
bool timerFired = false;
bool switchPressed = false;

//Interrupt service routine for handling the timeout
void sw1TimeOutHandler() {
    timerFired = true;
    sw1TimeOut.detach();        //Stop the timeout counter firing
    sw1.fall(&sw1FallingEdge);  //Now wait for a falling edge
}

//Interrupt service routive for SW1 falling edge (release)
void sw1FallingEdge() {
    switchPressed = true;
    sw1.fall(NULL);                             //Disable this interrupt
    red_led = !red_led;                         //Toggle LED    
    sw1TimeOut.attach(&sw1TimeOutHandler, 0.2); //Start timeout counter    
}

//Main - only has to initialise and sleep
int main() {
    
    //Initial state
    red_led    = 0; //Set RED LED to OFF
    green_led  = 1;
    
    //Configure interrupts, wait for first rising edge
    sw1.fall(&sw1FallingEdge);
    
    //Main Polling Loop
    while (true) {
        
        //Put CPU back to sleep
        sleep();
        
        //You can ONLY reach this point if an ISR wakes the CPU - now there are two
        if (timerFired == true) {
            timerFired = false;        //Reset flag
        }
        if (switchPressed == true) {
            switchPressed = false;      //Reset flag
            green_led = !green_led;
        }
    } //end while

}