Micro:bit uPython: Pausing the program execution

In this short tutorial we will check how we can pause the execution of a program on the Micro:bit, running MicroPython.

Introduction

In this short tutorial we will check how we can pause the execution of a program on the Micro:bit, running MicroPython.

In order to be able to pause the execution, we will use the sleep function of the microbit module. This function receives as input the number of milliseconds to pause the execution.

In our simple example, we will do a loop and print the current iteration value, waiting one second at the end of each iteration.

The code

As mentioned before, the sleep function is available on the microbit module. So, we need to import the function first, before using it.

from microbit import sleep

After that, we will specify our loop. We will do a simple for in loop between 0 and 9. We will use the range function to generate the list of numbers between 0 and 9 and iterate through each number of the list.

Note that the range function receives as first parameter the starting value of the list (included) and as second input the last number of the list (not included). This is why we use 10 as second argument of the range function, to generate the numbers between 0 and 9.

for i in range(0, 10):
#loop body

Then, inside the loop, we will simply print the current value and then pause the execution for 1 second. Since the sleep function receives the time in milliseconds, we need to pass to it the value 1000.

print (i)
sleep(1000)

The final code can be seen below.

from microbit import sleep

for i in range(0, 10):
  print (i)
  sleep(1000)

Testing the code

To test the code, simply upload the previous script to your Micro:bit board using a tool of your choice. In my case, I’m using uPyCraft, a MicroPython IDE.

After running the program, you should get an output similar to figure 1, which shows the numbers getting printed. During the program execution, there should be a 1 second delay between each print.

Printing numbers in a loop with 1 second delay, using micro:bit and uPython

Figure 1 – Output of the program.

Advertisements

4 Replies to “Micro:bit uPython: Pausing the program execution”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s