
The buttons are programmed so that when a particular button needs to be pressed for its respective colour to come on, it reads Turn (colour) On, and when the colour is on, the button reads Turn (colour) Off.
The configuration above has Red Off, Green ON and Blue ON, giving a beautiful cyan colour as in the picture below.
The Quit button is important - it closes the program down properly, so that all the GPIO ports are ready for the next program which may need to access them. If we just closed the window without using the Quit button, the program would continue listening for button presses, even though the window had disappeared. The Quit button, when pressed, invokes the Python function exit, which ensures a clean termination to the program.
The wiring part is exactly the same as the last post - 3 x 330Ω resistors, one between each of the red, green and blue RGB LED anodes and the Pi's GPIO ports 23, 24 and 25. The Draft Guinness widget is still doing its job admirably!
Here is the code:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Tkinter and GPIO together Matt Richardson, modified by S&S 2-Apr-15 | |
from Tkinter import * | |
import RPi.GPIO as GPIO | |
GPIO.setmode(GPIO.BCM) | |
GPIO.setup(23, GPIO.OUT) | |
GPIO.setup(24, GPIO.OUT) | |
GPIO.setup(25, GPIO.OUT) | |
GPIO.output(23, GPIO.LOW) | |
GPIO.output(24, GPIO.LOW) | |
GPIO.output(25, GPIO.LOW) | |
def toggleRed(): | |
if GPIO.input(23): | |
GPIO.output(23, GPIO.LOW) | |
toggleButtonRed["text"] = "Turn RED On" | |
else: | |
GPIO.output(23, GPIO.HIGH) | |
toggleButtonRed["text"] = "Turn RED Off" | |
def toggleGreen(): | |
if GPIO.input(24): | |
GPIO.output(24, GPIO.LOW) | |
toggleButtonGreen["text"] = "Turn GREEN On" | |
else: | |
GPIO.output(24, GPIO.HIGH) | |
toggleButtonGreen["text"] = "Turn GREEN Off" | |
def toggleBlue(): | |
if GPIO.input(25): | |
GPIO.output(25, GPIO.LOW) | |
toggleButtonBlue["text"] = "Turn BLUE On" | |
else: | |
GPIO.output(25, GPIO.HIGH) | |
toggleButtonBlue["text"] = "Turn BLUE Off" | |
root = Tk() | |
root.title("RGB Toggler") | |
toggleButtonRed = Button(root, text="Turn RED On", command=toggleRed, foreground="white", background="red") | |
toggleButtonRed.pack(side=LEFT) | |
toggleButtonGreen = Button(root, text="Turn GREEN On", command=toggleGreen, foreground="black", background="green") | |
toggleButtonGreen.pack(side=LEFT) | |
toggleButtonBlue = Button(root, text="Turn BLUE On", command=toggleBlue, foreground="white", background="blue") | |
toggleButtonBlue.pack(side=LEFT) | |
quitButton = Button(root, text=" Quit ", command=exit) | |
quitButton.pack(side=LEFT) | |
root.mainloop() |
Nice one Matt!
No comments:
Post a Comment