Fade LED in and out
Moderators: adafruit_support_bill, adafruit

Fade LED in and out

by hoxoh on Fri Apr 20, 2012 6:29 pm

I could use some help.
From the "Getting Started..." book by Banzi. I'm on example 4. I'm trying to take the LED fading in and out program and add a switch to turn it on and off. When I upload the sketch nothing happens until I push the button (so far so good) then the LED starts fading in and out. I push the button again and it has no effect, the LED continues fading in and out (not what I want). My sketch is posted below. I also tried an "if...else" in lieu of "while" but that didn't work either. My sense of it is that somehow I need to tell it to take a break from the fading in and out business and check the value of "state".
Many thanks.

//Fade LED in and out, switch toggles behavior on and off

const int LED = 9; //the pin for the LED
const int BUTTON = 7; //the input pin where the pushbutton is located
int i = 0; // use to count up and down
int val = 0; //val will be used to store the state of the input pin
int old_val = 0; //stores the previous value of "val"
int state = 0; // 0 = LED off while 1 = LED on

void setup () {

pinMode(LED, OUTPUT); //tells Arduino that LED is an output
pinMode(BUTTON, INPUT); //and BUTTON is an input

void loop() {
val = digitalRead(BUTTON); //read input value and store it

//check if there was a transistion
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state;

old_val = val; //val is now old, store it

while (state == 1)

for (i = 0; i < 255; i++) { //loop from 0 to 254 (fade in)
analogWrite(LED, i); //set the LED brightness
delay(10); // Wait 10ms because analogWrite
//is instantaneous and we would not see any change

for (i = 255; i > 0; i--) {//loop from 255 to 1 (fade out)
analogWrite(LED, i); // set the LED brightness
delay(10); // wait 10ms
Posts: 2
Joined: Sun Mar 25, 2012 6:36 pm

Re: Fade LED in and out

by adafruit_support_bill on Sat Apr 21, 2012 5:25 am

The "while", as you correctly suspected, will never exit. Once State goes to 1, there is nothing inside that loop to change it. Changing it to an "if" might help a little, but only if you press the button at the right time. Since there is no checking of the button while you are fading the LED, any button presses during that time will be missed.

You can add button checking inside the 'for' loops. A better way is to use an interrupt: http://arduino.cc/it/Reference/AttachInterrupt

Posts: 37628
Joined: Sat Feb 07, 2009 10:11 am

Re: Fade LED in and out

by hoxoh on Sat Apr 21, 2012 11:26 am

Thanks for the tip. I'm working on it.
Posts: 2
Joined: Sun Mar 25, 2012 6:36 pm