Raspberry Pi - LED - Fade

This tutorial instructs you how to program Raspberry Pi to fade LED. We will go through three examples and compare the differences between them:

Hardware Preparation

1×Raspberry Pi 4 Model B
1×LED
1×220 ohm resistor
1×Breadboard
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi
1×(Optional) Power Adapter for Raspberry Pi 4B
1×(Optional) Plastic Case for Raspberry Pi 4B

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of LED

The LED Pinout

LED has two pins:

  • The Cathode(-) pin needs to be connected to GND (0V)
  • The Anode(+) pin is used to control the LED's state
LED pinout

How It Works

Once the cathode(-) is connected to GND:

  • Connecting GND to the anode(+) will cause the LED to be OFF.
  • Connecting VCC to the anode(+) will cause the LED to be ON.
  • Generating a PWM signal to the anode(+) will adjust the brightness of the LED according to the PWM value. This value ranges from 0 to 255, with higher values causing the LED to be brighter and lower values causing it to be darker.
  • If the PWM value is 0, this is equivalent to GND and the LED will be OFF.
  • If the PWM value is 255, this is equivalent to VCC and the LED will be fully ON.
How LED Works

※ NOTE THAT:

For most LED, a resistor must be placed between the anode (+) and VCC. The value of the resistor is determined by the LED's specifications.

Raspberry Pi - fade LED

Some of the pins on a Raspberry Pi can be programmed to produce a PWM signal. To fade an LED, we can connect the anode (+) pin of the LED to a pin on the Raspberry Pi, the cathode (-) to ground, and program the Raspberry Pi to generate a PWM on the pin.

Wiring Diagram

The wiring diagram between Raspberry Pi and LED

This image is created using Fritzing. Click to enlarge image

How To Program

  • Set up a digital output on a Raspberry Pi's pin by using the GPIO.setup() function.
  • For instance, pin GPIO18:
GPIO.setup(18, GPIO.OUT)
pwm = GPIO.PWM(LED_PIN, 1000) pwm.start(0) pwm.ChangeDutyCycle(brightness)

The brightness can range from 0 to 100.

Raspberry Pi Code fades LED

Detailed Instructions

  • Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
  • Make sure your Raspberry Pi is connected to the same local network as your PC.
  • Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
  • If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
  • Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
  • Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Create a Python script file led_fade.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-led-fade """ import RPi.GPIO as GPIO from time import sleep LED_PIN = 18 fadePercent = 5 brightness = 0 GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN,GPIO.OUT) pwm = GPIO.PWM(LED_PIN, 1000) pwm.start(0) try: while True: pwm.ChangeDutyCycle(brightness) # change the brightness for next time through the loop: brightness = brightness + fadePercent; # reverse the direction of the fading at the ends of the fade: if brightness <= 0 or brightness >= 100: fadePercent = -fadePercent; # wait for 30 milliseconds to see the dimming effect sleep(0.03); finally: GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 led_fade.py
  • Check out the brightness of the LED.

The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

※ NOTE THAT:

The example above uses the time.sleep() function to create a fade-in and fade-out effect. The time.sleep() function, however, makes the LED fade in an unsmooth manner and blocks other code from running. In the upcoming sections, we will learn how to fade-in and fade-out smoothly without blocking other code by using the millis() function.

How to fade in/out LED in a period without using time.sleep()

Detailed Instructions

  • Create a Python script file led_fade.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-led-fade """ import RPi.GPIO as GPIO import time LED_PIN = 18 FADE_PERIOD = 3000 FADE_IN_MODE = True FADE_OUT_MODE = False fadeMode = FADE_IN_MODE start_time = 0 brightness = 0 def _map(x, in_min, in_max, out_min, out_max): return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min) GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN,GPIO.OUT) pwm = GPIO.PWM(LED_PIN, 1000) pwm.start(0) start_time = time.time()*1000 try: while True: progress = time.time()*1000 - start_time if fadeMode == FADE_IN_MODE: if progress <= FADE_PERIOD: brightness = _map(progress, 0, FADE_PERIOD, 0, 100) print(brightness) pwm.ChangeDutyCycle(brightness) else: start_time = time.time()*1000 fadeMode = FADE_OUT_MODE progress = 0 if fadeMode == FADE_OUT_MODE: if progress <= FADE_PERIOD: brightness = 100 - _map(progress, 0, FADE_PERIOD, 0, 100) print(brightness) pwm.ChangeDutyCycle(brightness) else: start_time = time.time()*1000 fadeMode = FADE_IN_MODE progress = 0 finally: pwm.stop() GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 led_fade.py
  • Check out the brightness of the LED.

Video Tutorial

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!