Controlling the Brightness of an LED
You want to vary the brightness of an LED from a Python program.
The RPi.GPIO library has a pulse-width modulation (PWM) feature that allows you to control the power to an LED and its brightness.
To try it out, connect an LED as described in Recipe 9.1 and run this test program:
import RPi.GPIO as GPIO 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: duty_s = raw_input(“Enter Brightness (0 to 100):”) duty = int(duty_s) pwm_led.ChangeDutyCycle(duty) |
If you are using Python 3 rather than Python 2, change the command raw_input to just input.
Run the Python program, and you will be able to change the brightness by entering a number between 0 and 100:
pi@raspberrypi ~ $ sudo python led_brightness.py Enter Brightness (0 to 100):0 Enter Brightness (0 to 100):20 Enter Brightness (0 to 100):10 Enter Brightness (0 to 100):5 Enter Brightness (0 to 100):1 Enter Brightness (0 to 100):90 |
You can exit the program by pressing Ctrl-C.
Discussion
PWM is a clever technique where you vary the length of pulses while keeping the overall number of pulses per second (the frequency in Hz) constant. Figure 9-2 illustrates the basic principle of PWM.
At high frequencies, the measured PWM frequency varies somewhat from the frequency supplied as an argument. This may be something that changes in later versions of the PWM feature of RPi.GPIO.
You can change the PWM frequency by modifying this line:
pwm_led = GPIO.PWM(led_pin, 500) |
The value is in Hz, so in this case, the frequency is set to 500 Hz.
Table 9-2 compares frequencies specified in the second parameter to GPIO.PWM to the actual frequency on the pin measured with an oscilloscope.
I also found that as the frequency increased, its stability decreased. This means that this PWM feature is no good for audio, but plenty fast enough for controlling the brightness of LEDs or the speed of motors.
See Also
For more information on PWM, see Wikipedia.
Recipe 9.9 uses PWM to change the color of an RGB LED, and Recipe 10.3 uses PWM to control the speed of a DC motor.
For more information on using breadboard and jumper wires with the Raspberry Pi, see Recipe 8.10. You can also control the brightness of the LED with a slider control—see Recipe 9.8.
Table 9-2. Requested frequency against actual frequency | |
Requested frequency | Measured frequency |
50 Hz | 50 Hz |
100 Hz | 98.7 Hz |
200 Hz | 195 Hz |
500 Hz | 470 Hz |
1 kHz | 890 Hz |
10 kHz | 4.4 kHz |