Skip to content

Instantly share code, notes, and snippets.

@v2keener
Created October 6, 2014 20:26
Show Gist options
  • Save v2keener/8c040249b1c9170d0e4e to your computer and use it in GitHub Desktop.
Save v2keener/8c040249b1c9170d0e4e to your computer and use it in GitHub Desktop.
Arduino Off/On switch via semaphore
// This bitty program allows me to have a simple push button operate as if it were a toggle switch
int switchState = 0;
boolean isOn = true; // state of pin 3
boolean isFirstLoop = true; // mutex
void setup(){
// Set pins 2 and 3 to OUTPUT
for(int x = 2; x <=3; ++x){
pinMode(x, OUTPUT);
}
}
void loop(){ // Triggered 1000s of times per second
switchState = digitalRead(2);
if (switchState == LOW){ // button up
isFirstLoop = true;
}
else { // button down
if(isFirstLoop){ // We only want to toggle isOn once, hence this mutex
isOn = !isOn;
isFirstLoop = false;
}
}
if(isOn){
digitalWrite(3, HIGH);
}
else {
digitalWrite(3, LOW);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment