Building game show buzzers with a Raspberry Pi
The getBuzzers function – Lines 26 to 42
The getBuzzers
function watches the GPIO pins in a continuous loop. Once a button is pressed, the function returns the number of the player that buzzed in first. The line
while 1:
is Python syntax for "do this forever." Like any other loop, it can be escaped by using the break
command.
Each if
statement is identical except for the GPIO pin it is checking and the number it returns (if applicable). GPIO.input
accepts a single argument, which is the pin from which to get a value:
if GPIO.input ( 4 ) == GPIO.LOW: return 1 break
GPIO.LOW
is a constant. If GPIO.input
is equal to GPIO.LOW
, then the pin is currently grounded. In my case, that means the button is pressed. Once that happens, return 1
returns the player number, and break
exits the while
loop. (See the "Python and Indents" box for more about Python syntax.)
Python and Indents
Whereas languages like C and JavaScript use { } to separate code blocks, Python uses indentation and leading whitespace. This means that whitespace in Python is significant, and multiple spaces are not the same as a tab, even if they occupy the same amount of screen real estate. Consider the following:
a = 0 while a < 10: a = a + 1 print a print "I counted to 10!"
The last print
statement is at the same indent level as the while
, so it won't run until the loop is complete. It works the same way for function definitions, classes, and if/then/else. If a Python line ends with a colon, then any following lines must be indented until you reach the end of the function, loop, etc.
Putting It All Together
Pygame, curses, and RPi.GPIO are all good candidates for a project like this because they play well with others. Each library accesses its own resources and, in the case of Pygame and curses, provides utilities to run an event loop. At the same time, though, neither event loop is required.
The combination of Pygame and curses also allows two distinct interfaces: a public-facing graphical screen and a meaningful menu for the operator that doesn't affect the main screen.
Buy this article as PDF
Pages: 8
(incl. VAT)