Create a Reaction Timer in Python

Introduction

Let us make our first game that tests your reflexes, a Reaction Timer. The aim of the game is to press the button as fast as you can once you hear the tone. The buzzer will sound after a randomly number of seconds so there will be no cheating, and your time will be displayed on the screen. Challenge your friends to see who can get the fastest time!

What we will achieve

  • Attaching an add on board to the Raspberry Pi
  • Installing the Python module for the Pibrella
  • Read an input
  • Make some sound
  • Make a random number

Preparation

What we need

Setting up

With the Raspberry Pi unplugged, firmly push the Pibrella on to the GPIO pins.

Now plug in the HDMI/Composite cable for the screen, your USB mouse and keyboard and finally plug in the power cable. Wait for the Raspberry Pi to boot, and boot in to the desktop.

Open Terminal (Menu, Accessories, Terminal) and type the following commands:

sudo apt-get update

sudo apt-get install python-pip -y

sudo pip install pibrella

Step 1: Starting Python

  1. With the Raspberry Pi switched on and showing the desktop, click Menu, Accessories and then Terminal
  2. Type sudo idle. Idle is what we shall use to write our code in to control our reaction timer, so lets create a file to save our work in.
  3. Click File -> New Window.
  4. This new window is what we shall write our code. Any errors will be displayed in the window called Python Shell. Lets go ahead and save this by clicking File -> Save As, and give it a name like reactiontimer

Step 2: Need input

The Pibrella has a nice big button that we can use, buttons are known as inputs. An input gives the computer an instruction from the outside world, other inputs you know are the mouse and keyboard you are using.

  1. Python uses libraries called modules, and we import the libraries we want in to the script, so lets add the Pibrella module by typing import pibrella.
  2. We also want to be able to pause our script, and Python does this by a function called sleep, which is from the time module, so type on the next line; import time.
  3. So far the script will do nothing, as we have just imported the modules we need and we haven’t told it to do anything else. Lets make sure we have no errors so far by pressing F5, and clicking OK to save.
  4. If everything works, we should see in the first window
    >>> ========== RESTART ===========
    >>>
    >>>
  5. Now lets tell it to do something. In the reactiontimer.py window add the following code after the imports:
    while True:
      if pibrella.button.read() == 1:
        print "On"
      else:
        print "Off"
      time.sleep(0.1)
  6. Let’s run the script again, if everything is fine it should start scrolling Off down the screen. When you press the button it should change to On.

It’s easy to read an input in Python, in the script you should notice that 0 means Off, and 1 is On. We added the sleep of 0.1 seconds to slow the script down so we are able to read what state the button is in.

Step 3: What’s that noise?

Now we can read what the button says, let’s try making some noise!

  1. Remove all the lines of code up to if pibrella.button.read() == 1:, as we only want to play a sound once we press the button.
  2. There are a few sounds in the Pibrella library, which we will explore soon, but for the time being we shall use pibrella.buzzer.success(). So add an indent and put that line in, followed by time.sleep(2).
  3. As the buzzer is programmed to play the same note or sound until told to stop, we must therefore tell it to stop. This is easily done with pibrella.buzzer.stop().
  4. Test to make sure it works by pressing F5 and OK to save it.
  5. Everytime you press (or hold down) the button, it will make a small tune. See how different it is with trying out pibrella.buzzer.fail(), or pibrella.buzzer.note(2) and even pibrella.buzzer.alarm().

It may not be a replacement for a grand piano or keyboard, but it certainly works for giving an extra something to your games.

Step 4: And sleep!

Adding sleep into our code allows the script to pause while something happens. We have used sleep to play a note for 2 seconds before moving on to the next command. Sleep can be used for much more, so we shall try a few things now

  1. Start a new file, and start with import time, we will use a couple of functions contained within the time module.
  2. Let us pause the script for 5 seconds, by storing the current time, wait 5 seconds and minus is from the new time:
    now = time.time()
    time.sleep(5)
    print time.time() - now

    Sleeping in Python is counted in seconds, so if you want to do, say half a second, just put in 0.5.

  3. Now to press F5 and see what happens, you should receive an output similar to this:
    >>> ========== RESTART ==========
    >>> 5.00512981415 
    >>> ========== RESTART ==========
    >>> 5.0013217926 
    >>> ========== RESTART ========== 
    >>> 5.00514507294
    >>>
  4. Experiment with more times, you should see how handy the sleep function will be.

As you might have noticed, the timing isn’t exact, it is off by a few milliseconds. As good as Python is at keeping count, the Operating System; Linux in our case, isn’t perfect at keeping time as it has a lot of other jobs to keep track of.

Step 5: Randomisation

As well as sleeping, Python is also good at making random numbers, so lets try it out.

  1. Create a new file, and import random.
  2. And add print random.random(). This will tell Python to display on the screen a random number between 0 and 1.
  3. As the random number is quite small, we shall multiply it by 10, and it’s easily done with
    print random.random()*10

Step 6: Putting it all together

Now we have learnt what makes a reaction timer, let’s put it all together and make a working game to test our reactions.

  1. Putting everything we have covered should bring us to a fully working game:
    import random, time, pibrella
    time.sleep(2 + (8 * random.random()))
    pibrella.buzzer.fail()
    t=time.time()
    while pibrella.button.read()==0:
      time.sleep(0.001)
    print time.time()-t
  2. Press F5 to start the script. After a few seconds the buzzer will make a sound, press the button as quick as possible after which your time will be displayed on the screen.

Finishing Up

In this activity you have grasped the basics of sounding a buzzer, learnt how to pause a script, read button inputs and choose a random number, you can use the knowledge you have learnt to create even more awesome projects. If you want to try some more things based on this activity, see the Things to try section below.

Things to Try

Now you have completed this activity, how about trying to expand further by:

Adding indicators

How about adding pibrella.light.red.on() at the same time the buzzer sounds?

Celebration tune

To score less than 0.15 seconds is a good challenge, so how about adding a pibrella.buzzer.success() if you score less than 0.15

Replace print time.time()-t with:

s = time.time()-t
print s
if s < 0.15:
  time.sleep(2)
  pibrella.buzzer.success()

Doing this stores the time difference in s, and checks if the value is less than 0.15 seconds, of which if it is, plays the success tone.

Version 1.1 - 05/05/2015 - © 2015 Cyntech
Activity by Jason Barnett, Code by Zachary Igielman