3. Micro:bit Iteration (Event Loop)
3.1 What is a Loop?
A loop is used to repeat code.
A common loop in MicroPython is:
1 | |
This means:
- Run the code forever
- The program keeps repeating until stopped
3.2 Basic Event Loop Example
1 2 3 4 5 6 7 | |
What happens
- The program shows a heart
- Waits
- Clears the screen
- Repeats forever
3.3 How the Loop Works
Step-by-step:
- The program enters the loop (
while True) - Runs the code inside
- Goes back to the top
- Repeats again
This continues forever unless:
- The micro:bit is reset
- Power is removed
3.4 Indentation (VERY IMPORTANT)
Python uses indentation to define what belongs inside the loop.
Correct Example
1 2 3 4 5 6 7 | |
Both images repeat because they are inside the loop
Incorrect Example
1 2 3 4 5 6 7 | |
What happens
HAPPYrepeats foreverSADnever runs
3.5 Fix the Indentation
1 2 3 4 5 6 7 | |
3.6 Using Loops with Buttons
Loops are often used to check inputs like buttons.
1 2 3 4 5 6 7 | |
What happens?
- The program constantly checks button A
- Shows different images depending on input
3.7 Combining Loops and Functions
We can call functions inside a loop.
1 2 3 4 5 6 7 8 9 10 11 12 | |
What happens?
- The loop runs forever
- When button A is pressed → function runs
3.8 Example: Random Behaviour
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
What happens?
- A random number is generated
- The display shows for a random time
- Repeats forever
3.9 Summary
Loops allow us to:
- Repeat actions continuously
- Create interactive programs
- Build event-driven systems
Key Concepts
while True:→ infinite loop- Indentation → controls what repeats
- Functions → can run inside loops
- Inputs → (e.g. buttons) work well with loops
3.10 Practice Ideas (Micro:bit)
-
Create a loop that:
- Flashes a smiley face continuously
-
Create a program that displays "Hello
"