Created
June 3, 2015 12:05
-
-
Save rlogiacco/547c039b564fe305222d to your computer and use it in GitHub Desktop.
Pseudo Concurrency
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define LED_PIN 13 | |
#define BTN_PIN 2 | |
int volatile prog = 0; | |
void btnPress() { | |
// cycle over the available programs | |
// it can be done in a much compact and simpler way, but I believe this is the most | |
// simple and clear way to describe it | |
// some sort of debouncing would be required, but I don't add it here for sake of simplicity | |
if (prog == 0) { | |
prog = 1; | |
} else if (prog == 1) { | |
prog = 2; | |
} else if (prog == 2) { | |
prog = 0; | |
} | |
} | |
void setup() { | |
// sets the led pin as output | |
pinMode(LED_PIN, OUTPUT); | |
// sets the button pin as input pullup (LOW means button pressed, HIGH means button not pressed) | |
pinMode(BTN_PIN, INPUT_PULLUP); | |
// setup the serial port at 9600 Bps | |
Serial.begin(9600); | |
// detects button presses | |
attachInterrupt(0, btnPress, FALLING); | |
} | |
long lastSwitch = 0; | |
bool ledState = HIGH; | |
void oneHz() { | |
// every half a second change the led from ON to OFF and vice versa: blink at 1Hz frequency | |
if (millis() - lastSwitch > 500) { | |
// the trick is there is no delay() here | |
ledState = !ledState; | |
lastSwitch = millis(); | |
digitalWrite(LED_PIN, ledState); | |
} | |
} | |
void tenHz() { | |
// every 50ms change the led from ON to OFF and vice versa: blink at 10Hz frequency | |
if (millis() - lastSwitch > 50) { | |
// the trick is there is no delay() here | |
ledState = !ledState; | |
lastSwitch = millis(); | |
digitalWrite(LED_PIN, ledState); | |
} | |
} | |
void serialSend() { | |
// send one chunk of data over serial and return immediately: ensure the chunks are small so to | |
// avoid holding the MCU | |
if (millis() - lastSwitch > 1000) { | |
// the trick is there is no delay() here | |
Serial.println("WELCOME TO THE TEST PROGRAM"); | |
lastSwitch = millis(); | |
} | |
} | |
void loop() { | |
// the loop runs continously, the only thing it's doing is checking which `program` | |
// will be executed | |
// the important thing is to have the functions not holding the MCU, ever! | |
if (prog == 0) { | |
oneHz(); | |
} else if (prog == 1) { | |
tenHz(); | |
} else if (prog == 2) { | |
serialSend(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment