Fade LED in and out

For makers who have purchased an Adafruit Starter Pack, get help with the tutorials here!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
hoxoh
 
Posts: 2
Joined: Sun Mar 25, 2012 6:36 pm

Fade LED in and out

Post by hoxoh »

Hello,
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;
delay(10);
}

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
}
}
}

User avatar
adafruit_support_bill
 
Posts: 88086
Joined: Sat Feb 07, 2009 10:11 am

Re: Fade LED in and out

Post by adafruit_support_bill »

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

hoxoh
 
Posts: 2
Joined: Sun Mar 25, 2012 6:36 pm

Re: Fade LED in and out

Post by hoxoh »

Thanks for the tip. I'm working on it.

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino Starter Pack”