Skip to main content
1 of 5
Enric Blanco
  • 2.1k
  • 1
  • 14
  • 25

The Arduino loop() function makes the use of a while loop redundant in this case. Even worse: the way you've implemented that while loop prevents buttonState from being updated, thus entering a deadlock.

Try this instead:

// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
const int led = 13;
const int buttonPin = 2;

// declare state variable as global
bool buttonState = LOW;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  // initial state: LOW
  digitalWrite(led, LOW);
}

// the loop routine runs over and over again forever:
void loop() 
{
  // check if button has been pressed at the start of each loop() iteration
  buttonState = digitalRead(buttonPin);

  // do either one thing or another, according to buttonState
  switch (buttonState) {
    case LOW:
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second
      break;
    case HIGH:
      digitalWrite(led, LOW);
  }
}

As you can see, it first checks the value of the button, then executes code according to that.

NOTE: There are better ways to implement the functionality you're looking for, but I've just tried to do as few changes as possible to your code so you can grasp the specific problem that has been bugging you.

Enric Blanco
  • 2.1k
  • 1
  • 14
  • 25