# BBC micro:bit Timing

## Introduction

There are a couple of ways to deal with timing on the micro:bit. Both involve some work for you as a programmer.

## Running Time

The running_time() function tells you the number of milliseconds since you turned on the Microbit or reset it.

To find a way to do something with this on the Microbit, I've created a function to make images on the matrix consist of up to a set number of LEDs. This is to allow some form of counting that doesn't involve scrolling. There will be better ways to do this but this works and is clear.

```# function to create an image consisting of value LEDs
def nleds(value):
img = m.Image('00000:'*5)
sp = img.set_pixel
counter = 0
for row in range(0,5):
for col in range(0,5):
if counter<value:
sp(col,row,9)
else:
sp(col,row,0)
counter += 1
return img```

The next program just adds dots, one every second. When the matrix is full, it starts again from 0. The program uses floor division, double division sign, to round a result down. The division by 1000 is to get seconds. The percent sign is the modulus and gives us the remainder, in the case after division by 26. This neatly makes for us a number from 0 to 25.

The sleep function is used to stop the matrix updating constantly.

```import microbit as m

# function to create an image consisting of value LEDs
def nleds(value):
img = m.Image('00000:'*5)
sp = img.set_pixel
counter = 0
for row in range(0,5):
for col in range(0,5):
if counter<value:
sp(col,row,9)
else:
sp(col,row,0)
counter += 1
return img

while True:
m.display.show(nleds(m.running_time()//1000 % 26))
m.sleep(100)
```

## Sleepy Time

The other way to do this is to use the sleep() function which you have been seeing in many of the examples. This means that you have to plan your program so that the delays you make by calling this function happen at the time you want.

```import microbit as m

# function to create an image consisting of value LEDs
def nleds(value):
img = m.Image('00000:'*5)
sp = img.set_pixel
counter = 0
for row in range(0,5):
for col in range(0,5):
if counter<value:
sp(col,row,9)
else:
sp(col,row,0)
counter += 1
return img

for i in range(1,26):
m.display.show(nleds(i))
m.sleep(1000)
m.display.clear()
```

## Challenges

1. You don't have to display a number of dots for your counting. You could use the digits 0 - 9. You could cycle through the alphabet or the clock images.
2. You can make a decent stopwatch if you include button interaction in your program.
3. You could use the buttons as a simple way to test reaction time. Do a 3-2-1 countdown and then, sleep for a random amount of time. The user should press a button when they see a particular image appear.
4. You could use the running_time() function to make a game like the compass calibration circle. Trying to do this quickly is quite hard. You could measure the time it takes the player to finish the circle and report this as a score.