Lara Grant

Press, Fade In, Press Fade Out

INPUT: 1 Momentary Button
OUTPUT: 1 LED

DESCRIPTION: Press button, LED fades on, press again, LED fades out.

[code lang=”arduino” light=”true”] /*
Press button, LED fades on then fades out

Created 1 Nov 2008
By David A. Mellis
modified 30 Aug 2011
By Tom Igoe
http://arduino.cc/en/Tutorial/Fading
This example code is in the public domain.

*/

int ledPin = 9; // LED connected to digital pin 9
int buttonPin = 2; // pin the puchbutton is connected
int buttonState = 0; // variable for reading the pushbutton status

void setup() {

// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {

// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == LOW ) {
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

// fade out from max to min in increments of 5 points:
for(int fadeValue = 255 ; fadeValue > 0; fadeValue -=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
else
{
digitalWrite(ledPin, LOW);
}
}

[/code]

Have your say