0

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
    You are constantly toggling it over and over again all the time you are holding the button down. Every iteration of loop() you change the variable to the opposite if you happen to still be holding the button down. – Majenko May 22 '17 at 23:12
  • @Manjenko, that makes sense! Thanks :) I have added a switch previous state variable to check and allow the if to only run when I want it. I'll post it up as an answer. – mysterious-bob May 22 '17 at 23:55
0

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 Jul 24 '17 at 3:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.