So, we can paint colours on the screen - let's do this from GPIs!
We'll use the four tactile buttons along the bottom of the screen to draw the GPIO number and a coloured background. From left to right the buttons correspond to GPIO #23, #22, #27, and #18.
(Note: If you have a revision 1 board then #27 is #21 - you'll just have to change the code a little)
Startup
The code is split into two sections: startup and main loop. Let's take a look at what's happening during startup.
This first section below imports a few things and then defines a datastructure for the four buttons. It's a simple map from GPIO number to RGB tuple. RGB tuples are used in a lot of pygame calls to set colors for fonts, backgrounds etc.
With the button map in place we can now loop through this and setup all the GPIOs. Each one needs to be set to an input with a pull-up since the buttons are connected to ground.
Finally in this startup section we initialise pygame. The os.putenv
call here is setting up an environment variable for SDL to tell it which frame buffer device we want to use. We then initialise pygame, hide the mouse pointer, set the display size and fill the background in black.
import pygame import os from time import sleep import RPi.GPIO as GPIO #Note #21 changed to #27 for rev2 Pi button_map = {23:(255,0,0), 22:(0,255,0), 27:(0,0,255), 18:(0,0,0)} #Setup the GPIOs as inputs with Pull Ups since the buttons are connected to GND GPIO.setmode(GPIO.BCM) for k in button_map.keys(): GPIO.setup(k, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Colours WHITE = (255,255,255) os.putenv('SDL_FBDEV', '/dev/fb1') pygame.init() pygame.mouse.set_visible(False) lcd = pygame.display.set_mode((320, 240)) lcd.fill((0,0,0)) pygame.display.update() font_big = pygame.font.Font(None, 100)
Main loop
Here we scan through the GPIOs to see if the buttons are pressed. We simply loop over the map we created earlier pulling out the GPIO number and the RGB tuple into k and v. If the GPIO is set False then the button is down. In which case we fill the background with the color referenced by v and then draw the text of the GPIO number.
Note the sleep(0.1)
call at the end of the loop. This simply ensures that our program is yielding and not running at 100% CPU usage.
while True: # Scan the buttons for (k,v) in button_map.items(): if GPIO.input(k) == False: lcd.fill(v) text_surface = font_big.render('%d'%k, True, WHITE) rect = text_surface.get_rect(center=(160,120)) lcd.blit(text_surface, rect) pygame.display.update() sleep(0.1)
You can also run this from the pygamelcd project:
sudo python test2.py
Page last edited January 24, 2016
Text editor powered by tinymce.