Guest

Fading Light Switch

By: a guest on Mar 5th, 2010  |  syntax: Java  |  size: 1.49 KB  |  hits: 289  |  expires: Never
download  |  raw  |  embed  |  report abuse
Copied
  1. // Fade an LED in and out when button pressed
  2. // Copyright 2010 by progmanos
  3. // Code license: GPL v.3 or later
  4. #define LED 9 // the pin for the LED
  5. #define BUTTON 7 // the input pin where the
  6.                  // pushbutton is connected
  7. int i = 0;    // We'll use this to count up and down
  8. int val = 0;  // val will be used to store the state
  9.               // of the input pin
  10. int old_val = 0;  // this variable stores the previous
  11.                   // value "val"
  12. int state = 0;  // 0 = LED off and 1 = LED on
  13.  
  14. void setup() {
  15.   pinMode(LED, OUTPUT);  // tell Arduino LED is an output
  16.   pinMode(BUTTON, INPUT); // and BUTTON is an input
  17. }
  18.  
  19. void loop() {
  20.   val = digitalRead(BUTTON);  // read input value and store it
  21.  
  22.   // check if there was a transition
  23.   if ((val == HIGH) && (old_val == LOW)) {
  24.     state = 1 - state;
  25.     delay(10);
  26.     for (i=0; i < 255; i++) { // loop from 0 to 254 (fade in)
  27.       analogWrite(LED, i); // set the LED brightness
  28.       delay(10);  // Wait 10ms because analogWrite
  29.                   // is instantaneous and we would
  30.                   // not see any change
  31.     }
  32.     delay(10);
  33.   }
  34.   else if ((val == HIGH) && (old_val == HIGH)) {
  35.     delay(10);
  36.     for (i = 253; i >= 0; i--) { // loop from 255 to 1 (fade out)
  37.       analogWrite(LED, i); // set the LED brightness
  38.       delay(10);           // Wait 10ms
  39.     }
  40.   }
  41.   else if (state == 0) {
  42.     digitalWrite(LED, LOW);
  43.   }
  44.  
  45.   old_val = val;  // val is now old, let's store it
  46.  
  47. }