I have a rotary encoder and I want to use the switch to stop the rest of my code running, essentially switching off what I have going on.
I have this
boolean running = true;
void setup() {
pinMode(swPin, INPUT);
digitalWrite(swPin, HIGH);;
}
void loop() {
if(digitalRead(swPin) == LOW) {
running = !running;
}
if(running) {
...
}
}
When I enter the if statement catching the switch press running does become false and the rest of the code is stopped. However, once released; running is becoming true again and the rest starts again.
I guess it is because the rotary encoder isn't fixed in the LOW state but I expected the running variable to be set to false and remain since it is declared outside of the loop().
Any guidance would be much appreciated!!
1 Answer 1
Thanks to @Manjenko's comment I was able to see my error.
Here is my solution:
boolean running = true;
int swReading;
int swPrevious = LOW;
void setup() {
pinMode(swPin, INPUT);
digitalWrite(swPin, HIGH);;
}
void loop() {
swReading = digitalRead(swPin);
if(swReading == LOW && swPrevious == HIGH) {
running = !running;
}
swPrevious = swReading;
if(running) {
...
}
}
-
This is still unlikely to reliably do what you want, due to contact bounce. To protect against that, add a fraction of a second of time where you ignore the input after deciding it has changed.Chris Stratton– Chris Stratton2017年07月24日 03:10:38 +00:00Commented Jul 24, 2017 at 3:10
loop()
you change the variable to the opposite if you happen to still be holding the button down.