Thursday, 26 January 2017

A simple reaction timer in MicroPython on the micro:bit

The micro:bit continues to surprise and delight me.

My project yesterday was to write a simple reaction timer in MicroPython.

The timer application was really easy to code. I'll build up a subset of the code step-by-step, but the whole program is on GitHub. You can download it here.

Here's how the code works:

The program starts by displaying a clock image:

Next, it picks a random time to wait, ranging from 500 ms to 4500 ms. (In other words, it will wait between half a second and four-and-a-half seconds.)

sleep(random.randint(500, 4500))

When the time has run out it displays a happy face: 

Then it checks every tenth of a second to see if the user has pushed button a (to show they have seen the image, keeping count while it waits.

def time():
    # returns the time until waiting is over, in 1/10 secs
    count = 0
    while waiting():
        sleep(100) # 100 ms = 1/10 secs
        count = count + 1
    return count

 The waiting() function just checks that button a has not been pressed yet:

def waiting():
    return not(button_a.is_pressed())

Once the user presses button a, the loop ends and the application prints out the time in tenths of a second.


When you look at the code you'll see that the current version does a little more than that. It runs in a loop, timing reactions over and over again, and continues until the user presses button b to exit.

It also checks to see if the user jumps the gun (naughty!) by pressing button a before the happy face is displayed.

Sample output

Here's the application output in mu's REPL window on the Pi:

I'm using the mu editor on a Raspberry Pi. mu allows you to opens a REPL window where you can type and execute Python code, and it also displays any output from print statements.

The next step will be an application that runs on a connected Raspberry Pi. It will capture the printed output and use it to do some clever calculations. I'll tell you about that in another blog post.

What fun projects are you doing with your micro:bit? I'd love to know. Just post a comment below.