Controlling the Brightness of an LED

In this example we will show you how to control the brightness of an LED connected . The RPi.GPIO library has a PWM feature that allows you to control the power to an LED and its brightness, we will use this in this example

 

Schematic

Fairly simple, simply connect an LED like this

 

This is a breadboard layout

Code

Save the following as pwm.py

[codesyntax lang=”python”]

import RPi.GPIO as GPIO

#pin 12 on GPIO header
led_pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)
pwm_led = GPIO.PWM(led_pin, 500)
pwm_led.start(100)

while True:
	brightness = raw_input("Enter Brightness value (0 to 100):")
	duty_value = int(brightness)
	pwm_led.ChangeDutyCycle(duty_value)

[/codesyntax]

 

Testing

From a terminal run the program by typing in

sudo python pwm.py

You should now see a prompt, type in a value and press enter and observe the effect on the LED

 

 

Related posts

How to Measure Internet Speed In Python Using Speedtest

Samba Setup on a Raspberry Pi

Python PWM GUI example on a Raspberry PI

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Read More