Alex Glow
Published

Fade an LED: Arduino Basics

Tired of the same old on-off, on-off action? Learn the power of PWM!

BeginnerProtip1 hour16,476
Fade an LED: Arduino Basics

Things used in this project

Hardware components

Arduino 101
Arduino 101
...or pretty much any other Arduino
×1
LED (generic)
LED (generic)
×1
Resistor 100 ohm
Resistor 100 ohm
×1
Breadboard (generic)
Breadboard (generic)
×1
Jumper wires (generic)
Jumper wires (generic)
×1

Hand tools and fabrication machines

HW101 Marker
Hardware 101 HW101 Marker

Story

Read more

Schematics

LED fade circuit

Make sure to plug your LED into pin 9, or any other PWM pin (as long as it matches the code). The little tilde marks on the Arduino show you which pins will work.

Code

Arduino example sketch: "Fade"

C/C++
/*
 Fade

 This example shows how to fade an LED on pin 9
 using the analogWrite() function.

 The analogWrite() function uses PWM, so if
 you want to change the pin you're using, be
 sure to use another PWM capable pin. On most
 Arduino, the PWM pins are identified with 
 a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.

 This example code is in the public domain.
 */

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

Credits

Alex Glow

Alex Glow

149 projects • 1583 followers
The Hackster team's resident Hardware Nerd. I love robots, music, EEG, wearables, and languages. FIRST Robotics kid.

Comments