Objective
Learn to detect button presses using Python on the micro:bit and display different messages when Button A or Button B is pressed.
Background
Your micro:bit has two built-in buttons: A (left) and B (right). In Python:
button_a.is_pressed()→ True when A is pressed; otherwise False.button_b.is_pressed()→ True when B is pressed; otherwise False.
Step-by-Step Instructions
- Open the micro:bit Python editor.
- Delete any starter code.
- Paste the following program and flash it to your micro:bit.
- You MUST NOT use any of the images below.
- You must find you own.
from microbit import *
while True:
if button_a.is_pressed():
display.show("A")
elif button_b.is_pressed():
display.show("B")
else:
display.clear()
How it works: The loop runs forever. If A is pressed, show “A”; else if B is pressed, show “B”; otherwise clear the display.
Your Task
- Change Button A to show a happy face.
- Change Button B to show a sad face.
- Add a third case: if both A and B are pressed at the same time, show a surprised face.
Hint: use Image.HAPPY, Image.SAD, and Image.SURPRISED.
Sample Solution (for checking)
from microbit import *
while True:
if button_a.is_pressed() and button_b.is_pressed():
display.show(Image.SURPRISED)
elif button_a.is_pressed():
display.show(Image.HAPPY)
elif button_b.is_pressed():
display.show(Image.SAD)
else:
display.clear()
Challenge Extension This is REQUIRED
Swap faces for words: have Button A scroll YES and Button B scroll NO.
from microbit import *
while True:
if button_a.is_pressed():
display.scroll("YES")
elif button_b.is_pressed():
display.scroll("NO")
else:
display.clear()
The name of the file will be:
PX_lastname_AB_Button
Files to save on Google Drive under your class and submit to Google Classroom
PX_lastname_AB_Button.png— Screenshot inside Python editor showing your code.PX_lastname_AB_Button.py— Your Python source file.PX_lastname_AB_Button.txt— Plain-text copy of your code.PX_lastname_AB_Button.hex— Hex file to run on the physical micro:bit.PX_lastname_AB_Button.mp4— Short demo video of the program running on the board.
Submission requirements
- Show the real micro:bit hardware running your program to Mr. Cusack.
- Get the secret code word after you demo.
- Include that exact code word in your Google Classroom submission comments.