
Fading Light Switch
By: a guest on Mar 5th, 2010 | syntax:
Java | size: 1.49 KB | hits: 289 | expires: Never
// Fade an LED in and out when button pressed
// Copyright 2010 by progmanos
// Code license: GPL v.3 or later
#define LED 9 // the pin for the LED
#define BUTTON 7 // the input pin where the
// pushbutton is connected
int i = 0; // We'll use this to count up and down
int val = 0; // val will be used to store the state
// of the input pin
int old_val = 0; // this variable stores the previous
// value "val"
int state = 0; // 0 = LED off and 1 = LED on
void setup() {
pinMode(LED, OUTPUT); // tell Arduino 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 transition
if ((val == HIGH) && (old_val == LOW)) {
state = 1 - state;
delay(10);
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
}
delay(10);
}
else if ((val == HIGH) && (old_val == HIGH)) {
delay(10);
for (i = 253; i >= 0; i--) { // loop from 255 to 1 (fade out)
analogWrite(LED, i); // set the LED brightness
delay(10); // Wait 10ms
}
}
else if (state == 0) {
digitalWrite(LED, LOW);
}
old_val = val; // val is now old, let's store it
}