Last active
August 29, 2015 13:59
-
-
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.
This file contains 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
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