![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
Toggle 2 Leds with two switches
Fork of Task324Solution by
main.cpp
- Committer:
- martinjamesallen1991
- Date:
- 2018-03-10
- Revision:
- 2:1874cdaec623
- Parent:
- 1:b7cc6bbb077d
File content as of revision 2:1874cdaec623:
#include "mbed.h" DigitalOut red_led(D7); DigitalOut green_led(D5); DigitalIn SW1(D4); DigitalIn SW2(D3); Timer tmr1; Timer tmr2; #define WAITING4PRESS 0 #define WAITING4BOUNCE_RISING 1 #define WAITING4RELEASE 2 #define WAITING4BOUNCE_FALLING 4 void updateState(int sw, int &swState, DigitalOut &led, Timer &tmr) { switch (swState) { //Waiting for switch to be pressed case WAITING4PRESS: if (sw == 1) { //Output: start timer tmr.reset(); tmr.start(); //Next state swState = WAITING4BOUNCE_RISING; } break; //Waiting for 50ms to elapse case WAITING4BOUNCE_RISING: if (tmr.read_ms() > 50) { //Outputs: Stop timer tmr.stop(); //Next state swState = WAITING4RELEASE; } break; //Waiting for switch to be released case WAITING4RELEASE: if (sw == 0) { //Outputs: Toggle the LED and start timer led = !led; tmr.reset(); tmr.start(); //Next state swState = WAITING4BOUNCE_FALLING; } break; //Waiting 50ms for switch bounce case WAITING4BOUNCE_FALLING: if (tmr.read_ms() > 50) { //Outputs: Reset timer 1 tmr.stop(); tmr.reset(); //Next state: swState = WAITING4PRESS; } break; default: //Something has gone very wrong tmr.stop(); tmr.reset(); led = 0; swState = WAITING4PRESS; break; } //end switch } //end function int main() { //Initial state red_led = 0; //Set RED LED to OFF green_led = 0; //Switch state int sw1State = 0; int sw2State = 0; //Timers tmr1.stop(); tmr1.reset(); tmr2.stop(); tmr2.reset(); //Main Polling Loop while (true) { //Poll inputs (without blocking) int sw1 = SW1; int sw2 = SW2; updateState(sw1, sw1State, red_led, tmr1); updateState(sw2, sw2State, green_led, tmr2); } //end while }