Last active
April 10, 2019 15:47
-
-
Save Foadsf/b1e9820632d953705fcb49fc75c1f4fb to your computer and use it in GitHub Desktop.
push-buttin changing the state of an LED --> https://arduino.stackexchange.com/questions/63343/changing-state-of-an-led-using-a-pushbutton-leads-to-unstable-result
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 = 2; | |
const int ledPin = 7; | |
int buttonState = 0; | |
int lastButtonState = buttonState; | |
bool flag = true; | |
bool flag_ = flag; | |
volatile byte state = LOW; | |
volatile byte state_ = state; | |
void setup() { | |
pinMode(ledPin, OUTPUT); | |
pinMode(buttonPin, INPUT); digitalWrite(buttonPin, HIGH); | |
attachInterrupt(digitalPinToInterrupt(buttonPin), changeState, FALLING); | |
} | |
void loop() { | |
buttonState = digitalRead(buttonPin); | |
if (buttonState == HIGH && lastButtonState != buttonState) { | |
flag = !flag; | |
} | |
if (state != state_ || flag != flag_) { | |
digitalWrite(ledPin, flag ? LOW : HIGH); | |
} | |
flag_ = flag; | |
state_ = state; | |
lastButtonState = buttonState; | |
// delay(5); | |
} | |
void changeState() { | |
state = !state; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment