Fading an LED from a switch

This example uses a digital input to control a fading LED. The LED turns on when the switch goes from off to on, then fades slowly to black.  It illustrates two principles:  the idea of edge detection or state change detection, and the idea of time delay without using delay().


int lastState = 0;          // last state of the switch
int currentState = 0;     // current state of the switch
int ledLevel = 0;           // level of the LED analogWrite
long lastFadeTime = 0;  // last time you decremented the LED level

void setup() {
  pinMode (2, INPUT);       // the switch pin
  pinMode(6, OUTPUT);     // the LED pin
  Serial.begin(9600);        // initialize serial communication
}



void loop() {
  // read the switch:
  currentState = digitalRead(2);

  // if the switch has changed, do something:
  if (currentState != lastState) {
    // if the switch is high:
    if (currentState == 1) {
      // set the LED level
      ledLevel = 255;
      Serial.println("turned on");
    } 
    // save the current state of the switch as the last state for next time through:
    lastState = currentState;
  }

  if (millis() - lastFadeTime > 5) {
    // fade the LED level:
    if (ledLevel >0 ) {
      // turn on or off the LED
      analogWrite(6, ledLevel);
      // decrement the LED level:
      ledLevel--; 
    } 
    else {
      // turn the LED off:
      digitalWrite(6, LOW); 
    }
    // note the last time you faded the LED:
    lastFadeTime = millis();
  }
}