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

