Skip to content

Instantly share code, notes, and snippets.

@nickswalker
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickswalker/10560819 to your computer and use it in GitHub Desktop.
Save nickswalker/10560819 to your computer and use it in GitHub Desktop.
How to make a toggle switch from a push-button using software. Call a function in the main loop that changes the toggle variables state only when it picks up changes in the pin state. Differentiates between button press and button release.
const int buttonPin = 5;
const int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}
void loop() {
digitalWrite(ledPin, checkToggleState(buttonPin));
}
int state = HIGH;
int buttonState; // the current reading from the input pin
int checkToggleState(int buttonPin){
int reading = digitalRead(buttonPin);
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
//Button went HIGH
if (buttonState == HIGH) {
Serial.println("Button pressed");
state = !state;
}
//Button went LOW
else {
Serial.println("Button released");
}
}
return state;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment