DEV Community

Cover image for Fading an LED with Arduino
AMANI Eric
AMANI Eric

Posted on

Fading an LED with Arduino

In this tutorial I will show you how you can make an LED fade using Arduino.

Materials Needed:

  • Arduino Board (e.g., uno)
  • Breadboard and jumper wires
  • LED
  • Resistor (270Ω)
  • USB cable for Arduino
  • Arduino IDE installed on your computer

Step 1: Set Up the Hardware:

  1. Connect the short leg (cathode) of the LED to GND on the Arduino.
  2. Connect the long leg (anode) of the LED to a resistor (270Ω) and to pin 13 on the Arduino. (Use a jumper wire for it to reach the Arduino pin)

Before we continue, here is how I arranged the components on the breadboard. (Insert an image of the new circuit)

Image description
Image description

Step 2: Connect your Arduino board to your computer:

Use the appropriate cable for your Arduino board.

Step 3: Writing the Code:

// Fading a single LED
int ledPin = 13; // Pin number for the LED

void setup() {
  pinMode(ledPin, OUTPUT); // Set the LED pin as an output

}

void loop() {
 for (int brightness = 0; brightness <= 255; brightness++) {
    analogWrite(ledPin, brightness);
    delay(5); // Adjust the delay for the desired fade speed
  }

  // Fade out
  for (int brightness = 255; brightness >= 0; brightness--) {
    analogWrite(ledPin, brightness);
    delay(5); // Adjust the delay for the desired fade speed
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Uploading the Code:

Make sure that in your Arduino IDE, the correct board is selected, and click on the upload button.

Your code should be uploaded successfully.

Test Your Fading LED:
Run the uploaded code on your Arduino board, and you should observe the LED fading in and out, creating a smooth fading effect.

Happy coding! ✨

You can what a demo here at the end of this article

Top comments (0)