0

I'm looking to have a button that, when pressed down, will mean that the script loaded on the Arduino doesn't run. So far I have:

void setup() {
  pinMode(3, INPUT_PULLUP);
  if (digitalRead(3) == LOW) {
    while(1);
  }
  // Beginning the Keyboard stream
  Keyboard.begin();
  // then the rest of the code.

I have a push button soldered to the ground and 3 pin. Could you see what is wrong with the code?

  • 5
    Well the while(1); will mean that the code will stop cold. Even if you release the button, the code will not resume. – Andre Courchesne May 2 '17 at 18:22
  • 2
    @AndreCourchesne Since that code is in setup() it will only get called if the button is closed when the Arduino starts up. – Johnny Mopp May 2 '17 at 18:27
  • @JohnnyMopp true indeed. – Andre Courchesne May 2 '17 at 18:28
  • 1
    aside: compiled code is not a "script"... – dandavis May 2 '17 at 18:49
  • Welcome to Arduino SE. Be sure to take the tour to see how things work here: arduino.stackexchange.com/Tour – SDsolar May 2 '17 at 20:09
1

I would do it this way:

void setup () {
    pinMode(3, INPUT_PULLUP);
}
void loop () {
    while (digitalRead(3)==LOW) {}; //do nothing, wait for release button
    // do all my stuff
}

or even better I would use some LED to indicate, that the button is pressed (or released) to have some visual state indicator (or another stuff to do while the button is pressed

void setup () {
    pinMode(3, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    digitalWrite(13,LOW);
}
void loop () {
    while (digitalRead(3)==LOW) {
       digitalWrite(13,HIGH); // let it shine
       };
    digitalWrite(13,LOW);
    // do all my stuff
}

eventually

void setup () {
    pinMode(3, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    digitalWrite(13,LOW);
}
void loop () {
    if (digitalRead(3)==LOW) {
       digitalWrite(13,HIGH); // let it shine
       while (digitalRead(3)==LOW) {
          // do some other stuff
       };
    digitalWrite(13,LOW); // switch indicator off
    // do my regular stuff
}
-1

You need to move the code that checks the button into loop(). Put the code that you want to pause in the if block.

void loop() {
    // Only execute if not pressed
    if (digitalRead(3) != LOW) {
        // Do stuff
    }
}

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.