MicroPython — loops and working with time

Lesson 4 of 17 · MicroPython and the micro:bit

Almost every micro:bit program uses repetition and pauses. Without loops and control of time we cannot make animations, games, counters or projects with sensors.

In this lesson you will learn how to:

  • use while True (an infinite loop)
  • make pauses with sleep()
  • understand the difference between fast and controlled execution
  • combine loops, time and buttons

The infinite loop — while True


Micro:bit programs usually run all the time while the device is switched on. That is why we use an infinite loop.


from microbit import *

while True:
    display.show(Image.HEART)

The program keeps running the code inside the loop. If there is no sleep(), the micro:bit will repeat the same command very fast, again and again.


What happens without a pause?

If we check a button in a loop without a pause, the program can become "too fast".


from microbit import *

while True:
    if button_a.is_pressed():
        display.show(Image.HAPPY)

This code works, but the processor keeps checking the state of the button. It is better to add a short pause:


from microbit import *

while True:
    if button_a.is_pressed():
        display.show(Image.HAPPY)
    sleep(50)  # a short 50 ms pause

This is more efficient and more stable.


A pause — sleep(ms)


The function sleep() stops the program for a certain time. The time is measured in milliseconds.

  • 1000 ms = 1 second
  • 500 ms = half a second
  • 100 ms = a very short pause

from microbit import *

display.show(Image.HAPPY)
sleep(1000)  # we wait 1 second
display.show(Image.SAD)

Animation with a loop


By combining while True and sleep() we can make animations.


from microbit import *

while True:
    display.show(Image.HAPPY)
    sleep(500)
    display.show(Image.SAD)
    sleep(500)

The pictures change every 0.5 seconds.


Example: a time counter

We can use a loop to make a simple counter.


from microbit import *

number = 0

while True:
    display.show(str(number))
    sleep(1000)  # we wait 1 second
    number = number + 1

This program shows the numbers 0, 1, 2, 3... every second.


Example: a blinking LED matrix

We can switch the screen on and off.


from microbit import *

while True:
    display.show(Image.SQUARE)
    sleep(300)
    display.clear()  # switches the LED matrix off
    sleep(300)

This makes a blinking effect.


Working with the function running_time()

MicroPython has the function running_time(), which returns the time since the program started (in ms).


from microbit import *

while True:
    time_ms = running_time()
    display.scroll(str(time_ms))
    sleep(2000)

This is useful for measuring reaction time or how long an event lasts.


Comparison with MakeCode


In MakeCode you use the blocks:

  • forever
  • pause (ms)

In MicroPython they are replaced by:

  • while True
  • sleep(ms)

You can look at the MakeCode version here:


Typical beginner mistakes


  • a forgotten sleep() → the program reacts too fast
  • a pause that is too long → it looks as if the program does not work
  • a forgotten while True → the code runs only once
  • forgotten indentation in the loop

Mini tasks

Task 1 (easier)

Make a program that shows a heart for 1 second, then an empty screen for 1 second — and so on, all the time.

Task 2 (medium)

Make a counter that counts from 0 to 9, then goes back to 0 and continues.

Task 3 (challenge)

When you press button A, run an animation for 3 seconds, then go back to the starting screen.


In which environment can you try these examples?

  • Thonny — use from microbit import *
  • the online MicroPython editor (python.microbit.org)
  • MakeCode Python — but adjust the syntax (basic.pause(), basic.show_icon())

What have you learned?

  • how an infinite loop works
  • how we control the speed of a program
  • how an animation is made
  • how to make a counter
  • how to measure running time

Hidden mini quiz — loops and working with time

Click on the quiz and check whether you understand the basic concepts of the while loop and the sleep() function.

Open the quiz

Mini quiz: loops and time

1. What does while True: do in MicroPython?




2. How long does sleep(1000) last?




3. What happens if we forget sleep() in a loop that checks a button?




4. Which function returns the time since the program started, in milliseconds?




5. What will this program show?


from microbit import *

number = 0
while True:
    display.show(str(number))
    sleep(500)
    number = number + 1






Mini tasks (explained in detail)


Task 1

Show the numbers from 0 to 4 on the LED matrix, with a 500 ms pause between the numbers.


from microbit import *

for i in range(5):
    display.show(str(i))  # Shows the current number
    sleep(500)            # A half-second pause

Step by step:

  • We create a sequence of numbers with range(5)
  • We show each number using display.show()
  • We add a pause with sleep() so that the numbers can be seen

Task 2

Show the happy and the sad face one after the other, 3 times.


from microbit import *

frames = [Image.HAPPY, Image.SAD]

for n in range(3):
    for f in frames:
        display.show(f)
        sleep(500)  # Half a second between the pictures

Note:

  • Using a for loop inside a loop lets the animation repeat several times
  • You can change the length of the pause for a faster or slower animation

Task 3

Show a counter that goes from 0 to 9, and when it reaches 9, goes back to 0 and continues forever.


from microbit import *

number = 0
while True:
    display.show(str(number))
    sleep(300)
    number += 1
    if number > 9:
        number = 0  # Resetting the counter

Explanation:

  • The infinite loop while True keeps running the code
  • The pause sleep(300) slows down the display of the numbers
  • We reset the number when it goes past 9

Task 4

Press button A to show a heart ❤️, and button B to show a sad face.


from microbit import *

while True:
    if button_a.is_pressed():
        display.show(Image.HEART)
    elif button_b.is_pressed():
        display.show(Image.SAD)
    else:
        display.clear()  # An empty screen if nothing is pressed

Instructions:

  • We check the state of the buttons with is_pressed()
  • We combine if/elif/else for different reactions

Task 5

Create an animation that shows hearts of different sizes, pausing 200 ms between the changes, and repeat it forever.


from microbit import *

frames = [Image.HEART_SMALL, Image.HEART, Image.HEART_SMALL]

while True:
    for f in frames:
        display.show(f)
        sleep(200)

Note:

  • First step: make a list of pictures
  • Second step: a loop that goes through the list
  • Third step: a pause between the pictures

Mini tasks for independent work


Task 6

Show the text "HI" on the LED matrix every 2 seconds, forever.

Task 7

Make a counter that goes from 0 to 5 and then back down to 0, and repeat it forever. Use while True and sleep().

Task 8

Make an animation of 4 different symbols (a heart, a smile, a sad face, a square) that changes every 0.5 seconds.

Task 9

When button A is pressed — "A" is shown, when button B is pressed — "B" is shown, and when both buttons are pressed — show a heart. The program keeps checking the buttons.

Task 10

Create a "digital clock" that shows the seconds from 0 to 9 on the LED matrix and resets when it reaches 9. Add a 1-second pause between the displays.


A note about the environments

✔ In Thonny you must write: from microbit import *

✔ MakeCode Python uses a different syntax for text and pictures, for example basic.show_string("HI") or basic.show_icon(IconNames.HEART)

Connecting with other lessons: control statements and loops in MakeCode

To understand better how selection and loops are used in programs, look at the MakeCode version of the examples:

In MicroPython we apply the same concepts using:

  • if / elif / else — selection and flow control
  • while and for — loops
  • sleep(ms) — controlling the running time

Below are examples that connect these ideas.


3 tasks with instructions and solutions (MicroPython)


Task 1: Even numbers

Write a program that, when the device is shaken (shake), shows the even numbers from 0 to 10.

Explanation and solution:


from microbit import *

while True:
    if accelerometer.was_gesture("shake"):
        for i in range(0, 11):   # we go from 0 to 10
            if i % 2 == 0:        # we check whether the number is even
                display.show(i)
                sleep(300)
        display.clear()

✔ This task combines the for loop and the if statement
✔ The code runs only when the device is shaken — the idea of the MakeCode "on shake" block.


Task 2: Counting up to a condition

Write a program that counts from 0 upwards until it reaches the value 7, and then shows "OK".

Explanation and solution:


from microbit import *

number = 0
while number <= 7:       # the loop repeats while number ≤ 7
    display.show(str(number))
    sleep(400)
    number += 1          # we increase the number

display.scroll("OK")

✔ Here we use a while loop with a condition instead of an infinite one
✔ After the loop ends we show a message — the concept of flow control.


Task 3: Temperature control

Write a program that keeps measuring the temperature and:

  • if the temperature is ≥ 25°C — shows an arrow pointing up ↑
  • otherwise — shows an arrow pointing down ↓

Explanation and solution:


from microbit import *

while True:
    t = temperature()  # we read the temperature
    if t >= 25:
        display.show(Image.ARROW_N)  # arrow pointing up
    else:
        display.show(Image.ARROW_S)  # arrow pointing down
    sleep(500)

✔ This example combines a loop and selection
✔ It is like the MakeCode examples that choose what to do based on the temperature.


These examples show you how to turn the same ideas from the MakeCode tutorials into real MicroPython code, using while, for, if / else and sleep().


Hidden mini quiz — loops and selection

Click on the quiz and check your understanding of:

  • how to use while and for loops
  • how to use if / else for decisions
  • how to combine selection and time (sleep())
Open the quiz

1. What will happen when you run the following code?


from microbit import *

while True:
    display.show("5")



2. How do you show the numbers 0 to 5 one by one with a 500 ms pause?


from microbit import *

# your code here



3. Which line of code checks whether the temperature is ≥ 25°C?


t = temperature()
# ? 



4. What does sleep(1000) do in MicroPython code?




5. What happens with the following code?


from microbit import *

while True:
    if button_a.is_pressed():
        display.show("A")
    else:
        display.clear()




Related: the same topic in MakeCode and other lessons

If you worked with the micro:bit in blocks in the 5th or 6th grade, compare the blocks with the MicroPython code: