Sunday, November 17, 2013

Fade LED In and Out with Arduino

You can fade out and fade in the light of an LED automatically by using Arduino and a simple code that is described below. Even though the Arduino board cannot output variable voltage on its digital pins there is a way to generate a rectangular signal that walks periodically between 0V and 5V.

 
 
 
 

 CODE :

 
 
 
int i = 0;
const int LED = 11; //define the pin we use for LED

void setup() {
  pinMode(LED, OUTPUT); //set pin 11 as OUTPUT
}

void loop() {
    for (int i = 0; i < 255; i++)
{ //if i is less than 255 then increase i with 1
    analogWrite(LED, i); //write the i value to pin 11
    delay(5); //wait 5 ms then do the for loop again
  }
  for (int i = 255; i > 0; i--){ //descrease i with 1
    analogWrite(LED, i);
    delay(5);
  }
}
 
 
 
 
 
 
 
 
 
 
 
Arduino Uno connections schematic
arduino fading led schematic
According to how long it stays in 5V and 0V (using the delay() function) you can obtain the fade effect. If delay() has a low value (for example 50ms or 0.05s) the fading speed will be higher because the Arduino will keep the voltage at pin 11 at a certain value only for 50ms then executes the next for() loop.
When the light intensity reaches the highest point then the second for() loop enters in action. This one will decrease the value of the output voltage on pin 11.


You might notice that the fading effect is not liniar; this is due the fact that the difference in light intensity is not so obvious after a certain voltage level and that is why it will appear like the LED lights longer than it stays OFF.
 
 

No comments:

Post a Comment