Holooly Plus Logo

Question 9.8: You want to make an application to run on the Raspberry Pi t......

You want to make an application to run on the Raspberry Pi that has a slider to control power to a device using PWM.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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):
frame = Frame(master)
frame.pack()
scale = Scale(frame, from_=0, to=100,
orient=HORIZONTAL, command=self.update)
scale.grid(row=0)
def update(self, duty):
pwm.ChangeDutyCycle(float(duty))
root = Tk()
root.wm_title(‘PWM Power Control’)
app = App(root)
root.geometry(“200×50+0+0”)
root.mainloop()

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).

9.9

Related Answered Questions

Question: 9.11

Verified Answer:

Assuming you have a 5V volt meter, you can use a P...
Question: 9.10

Verified Answer:

The way to do this is to use a technique called Ch...
Question: 9.9

Verified Answer:

Use PWM to control the power to each of the red, g...
Question: 9.7

Verified Answer:

Using the Tkinter user interface framework, write ...
Question: 9.5

Verified Answer:

Use a relay and small transistor. Figure 9-5 shows...
Question: 9.1

Verified Answer:

Connect an LED (see “Opto-Electronics” on page 381...
Question: 9.3

Verified Answer:

Use a piezo-electric buzzer connected to a GPIO pi...
Question: 9.4

Verified Answer:

These high-power LEDs use far too much current to ...
Question: 9.6

Verified Answer:

Use a PowerSwitch Tail II (see “Modules” on page 3...