Fernando RGaribay
/
InfInd-Buttons
Simple example on buttons. Currently untested.
main.cpp
- Committer:
- rgaribay
- Date:
- 2015-11-06
- Revision:
- 0:2d148f94a249
File content as of revision 0:2d148f94a249:
// Quick example on buttons // By Fernando R. #include "mbed.h" #include <iostream> #define DEBOUNCE_MS 25 DigitalIn button(PTE1); DigitalOut ledRed(LED_RED); DigitalOut ledGreen(LED_GREEN); DigitalOut ledBlue(LED_BLUE); enum State { VERDE, AMARILLO, ROJO, }; State nextState(State currentState); void executeState(State state); int main() { State currentState; while (1) { if (button) { currentState = nextState(currentState); } executeState(currentState); } } int main_alternative_for_only_once_on_press() { State currentState; int buttonThisCycle = 0; int buttonPreviousCycle = 0; while (1) { buttonThisCycle = button; if (buttonThisCycle && !buttonPreviousCycle) { currentState = nextState(currentState); } executeState(currentState); buttonPreviousCycle = buttonThisCycle; } } int main_alternative_for_only_once_on_press_with_debounce() { State currentState; int buttonThisCycle = 0; int buttonPreviousCycle = 0; Timer t; unsigned int timeLastPress = 0; t.start(); while (1) { buttonThisCycle = button; if (buttonThisCycle && !buttonPreviousCycle) { int timeSinceLastPress = t.read_ms() - timeLastPress; if (timeSinceLastPress > DEBOUNCE_MS) { timeLastPress = t.read_ms(); currentState = nextState(currentState); } } executeState(currentState); buttonPreviousCycle = buttonThisCycle; } } State nextState(State currentState) { switch (currentState) { case VERDE: return AMARILLO; break; case AMARILLO: return ROJO; break; case ROJO: return VERDE; break; default: std::cerr << "Invalid State"; } } void executeState(State state) { switch (state) { case VERDE: ledRed = 1; ledGreen = 0; ledBlue = 1; break; case AMARILLO: ledRed = 0; ledGreen = 0; ledBlue = 1; break; case ROJO: ledRed = 0; ledGreen = 1; ledBlue = 1; break; default: std::cerr << "Invalid State"; } }