Advertisement
arduino fading led schematic

Fade LED In and Out with Arduino – Tutorial #2

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.

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.

4 Comments

Join the conversation!

Error! Please fill all fields.
  • Kartikay

    When I is 255 it is the brightest and when it is 0 it is off, right?

  • vicky_vigia

    Thank you for your reply.
    Yes, I’ve created couple of MOSFET based circuits. We call them solid-state models 😛

    I am looking if I can put some logic, some other sensors and variable timings to it. So, considering Arduino!

    The logic can be sketched (I am a coder +10 years now) but I am not sure I do I manage the load of 10-15 x 100W bulbs.

    Can you guide me on this subject of Load!? 🙂

    Sincerely, Vicky

  • vicky_vigia

    Great!
    Thank you for this sketch too!

    Furthermore, how can I attach a 100W bulb, or several such bulbs to make them fade-in fade-out?

    Sincerely, Vicky

    • Popescu Marian

      You can use a MOSFET to accomplish this. Search on google “MOSFET light dimmer” and you will find some examples.

Looking for the latest from TI?