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.

4 thoughts on “Micro:bit uPython: Pausing the program execution”

  1. Pingback: Micro:bit uPython: using external pins for serial communication – techtutorialsx

  2. Pingback: Micro:bit uPython: using external pins for serial communication – techtutorialsx

  3. Pingback: Micro:bit uPython: Receiving data from serial port – techtutorialsx

  4. Pingback: Micro:bit uPython: Receiving data from serial port – techtutorialsx

  5. Pingback: Micro:bit uPyCraft: Pinging the UART OBLOQ – techtutorialsx

  6. Pingback: Micro:bit uPyCraft: Pinging the UART OBLOQ – techtutorialsx

  7. Pingback: Micro:bit uPython: Pinging the UART OBLOQ – techtutorialsx

  8. Pingback: Micro:bit uPython: Pinging the UART OBLOQ – techtutorialsx

Leave a Reply

Discover more from techtutorialsx

Subscribe now to keep reading and get access to the full archive.

Continue reading