You want to make an application to run on the Raspberry Pi that has a slider to control power to a device using PWM.
Using the Tkinter user interface framework, write a Python program that uses a slider to change the PWM duty cycle between 0 and 100 percent (Figure 9-9).
You will need to connect an LED or some other kind of output device to GPIO pin 18 that is capable of responding to a PWM signal. Using an LED (Recipe 9.1) is the easiest option to start with.
Open an editor (nano or IDLE) and paste in the following code. As with all the program examples in this book, you can also download the program from the Code section of http://www.raspberrypicookbook.com, where it is called gui_slider.py.
from Tkinter import * import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) pwm = GPIO.PWM(18, 500) pwm.start(100) class App: def __init__(self, master): |
Note that you will need to run it with sudo because the RPi.GPIO requires you to have superuser privileges to access the GPIO hardware.
$ sudo python gui_slider.py |
In Python 3, the Tkinter library has been renamed tkinter, with a lowercase t.
Discussion
The example program defines a class called App that contains most of the application code. The command option runs the update command every time the value of the slider is changed. This updates the duty cycle of the output pin.
See Also
You can use this program to control an LED (Recipe 9.1), a DC motor (Recipe 10.3), or a high-power DC device (Recipe 9.4).