Starting your first Raspberry Pi project? Here’s how to quickly install Raspberry Pi OS on your device.

What PWM Does to an LED

PWM, or Pulse Width Modulation, is a method that artificially lowers the voltage output of the Raspberry Pi’s GPIO (General Purpose Input/Output) pins. It’s artificial, as you don’t really reduce the voltage and just turn it on and off so fast that the overall voltage becomes lower than the real voltage you’re applying to it. For an LED or Light-Emitting Diode, increasing the overall voltage makes it shine brighter, while decreasing it makes it dimmer. But since the Raspberry Pi has no analog output, we’re using PWM to control the LED’s brightness.

What You’ll Need

2 pushbuttons 3 resistors (250-550Ω will work. Use a lower rating if the LED is too dark.) 1 LED (any color) Breadboard Jumper wires Raspberry Pi (any model except the Pi Pico)

How to Use PWM to Control LED Brightness on a Raspberry Pi

In this guide, we are using use two buttons to make the LED shine brighter or dimmer with PWM. Pressing the “brighter” button increases the PWM output, while pressing the “dimmer” button decreases it.

Preparing the Circuit

Note: to find the right pin number on the Raspberry Pi, hold the board so that the GPIO pin tray sits to the right. The top-left pin should be pin 1, to its right should be pin 2, and below should be pin 3. Tip: want to know more about pushbuttons? We have a full guide dedicated to showing you how to use pushbuttons with Raspberry Pi GPIO pins. If Python is your go-to programming language, learn how to install and manage multiple Python versions in Linux.

Preparing the Code

On your favorite code-editing tool, make a new file and save it as “rpi-lcdpwm.py.”

Final Code:

Making It Work

First, you’ll need a terminal. You can use the Raspberry Pi’s built-in terminal or control the Raspberry Pi through SSH on a separate computer. Through the terminal, you should go to the Python script’s directory and enter python3 rpi-ledpwm.py or the filename you used. Sometimes the LED will look like it’s blinking. The PWM frequency is probably too low, if that’s the case. You can increase the frequency by increasing the number in pwmLEDPin = GPIO.PWM(ledPin, 100) until the blinking is no longer noticeable. If you find the transitions to be grainy, lower the time in sleep(0.25) inside the while loop. It does get faster as you lower it, though, so don’t lower it too much. Tip: prefer Arduino instead? Here’s a complete guide to getting you started with Arduino projects. All images by Terenz Jomar Dela Cruz.