From GPIO to screen

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)


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.

Download: file
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
for k in button_map.keys():
    GPIO.setup(k, GPIO.IN, pull_up_down=GPIO.PUD_UP)
WHITE = (255,255,255)
os.putenv('SDL_FBDEV', '/dev/fb1')
lcd = pygame.display.set_mode((320, 240))
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. 

Download: file
while True:
    # Scan the buttons
    for (k,v) in button_map.items():
        if GPIO.input(k) == False:
            text_surface = font_big.render('%d'%k, True, WHITE)
            rect = text_surface.get_rect(center=(160,120))
            lcd.blit(text_surface, rect)

You can also run this from the pygamelcd project:

Download: file
sudo python
This guide was first published on Feb 01, 2016. It was last updated on Feb 01, 2016. This page (From GPIO to screen) was last updated on May 23, 2019.