While Loop

While loops perform a certain task as long as a the conditions in the parenthesis remain true. The unique thing about while loops is that as soon as a condition is no long true it will instantly stop performing the task. As you will notice with this basic while loop, as you press the button and the light slowly starts to light up, if you let go of the button the light will immediately turn off, instead of continuing to light up as it would in an if statement.

int Pin = 6; // choose a pin for the LED

int button = 2; // choose a pin for the push button

int x=0; // sets a variable for the fading

void setup()


pinMode(Pin, OUTPUT); // declares LED as an output

pinMode(button, INPUT); // declares push button as an input



void loop()


while (digitalRead(button) == HIGH && x<=255) // checks if the button is on and

// if the variable 'x' is less than 255


analogWrite(Pin,x); // the LED will fade as long as the

delay(20); // statements in the 'while' are true



x=0; // sets the variable 'x' back to zero

analogWrite(Pin, 0); // sets the LED off