This tutorial will explain how to dim an LED using PWM (Power with Modulation) with a Raspberry Pi. It should work on all current Raspberry Pi boards.
What is PWM?
A Pulse Width Modulation (PWM) Signal is a method for generating an analog signal using a digital source. A PWM signal consists of two main components that define its behavior: a duty cycle and a frequency. The duty cycle describes the amount of time the signal is in a high (on) state as a percentage of the total time of it takes to complete one cycle. The frequency determines how fast the PWM completes a cycle (i.e. 1000 Hz would be 1000 cycles per second), and therefore how fast it switches between high and low states. By cycling a digital signal off and on at a fast enough rate, and with a certain duty cycle, the output will appear to behave like a constant voltage analog signal when providing power to devices.
Attention: I am not responsible for any damage to your Raspberry Pi. Do this at your own risk!
What do you need?
- A Raspberry Pi
- A LED or more
- A resistor of 330 Ohm
- Jumper wire
Connecting the LED
- When you lookfrom the front of the LED:
- The left pin is the anode (+)
- The right pin is the cathode (-)
- At first put the LED in the breadboard
- Then connect the resistance to the LED
Connecting the Raspberry Pi
Here is a overview over the GPIO pins of the Raspberry Pi:
- At first connect one of the ground pins (like the Pin 6) to the ground bus of the breadboard
- Then connect the GPIO 26 (Pin 37) to the resistance
- Now connect the resistance to the anode of the LED
- Also connect the cathode to the negative bus of the breadboard
How it work?
Here there is the code for this project:
(I use the GPIO 26 so if you used another GPIO change the “26” with your correct pin)
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(26, GPIO.OUT)
p = GPIO.PWM(26, 50)
p.start(0)
try:
while True:
for i in range(100):
p.ChangeDutyCycle(i)
time.sleep(0.06)
for i in range(100):
p.ChangeDutyCycle(100-i)
time.sleep(0.06)
except KeyboardInterrupt:
pass
p.stop()
GPIO.cleanup()