2.11. Exercise: Light and Sound#
Navigate to the MicroPython editor https://python.microbit.org/v/3. If you already have it open, then use that existing window or tab.
Connect your micro:bit using the instructions on the previous page
Enter the following code into the editor
from microbit import *
while True:
display.clear()
if button_a.is_pressed():
display.set_pixel(0, 0, 9)
if button_b.is_pressed():
display.set_pixel(4, 0, 9)
sleep(100)
Flash the code to your micro:bit.
If you get stuck ask a peer or your teacher for help!
Question 1
Change the code so that:
When button A is pressed a happy face is shown on the display
When button B is pressed a sad face is down on the display
Solution
from microbit import *
while True:
display.clear()
if button_a.is_pressed():
display.show(Image.HAPPY)
if button_b.is_pressed():
display.show(Image.SAD)
sleep(100)
Question 2
Extend your code so that
When button A is pressed a happy sound is played
When button B is pressed a sad sound is played
You can choose your own sounds!
Solution
Solution is locked
Question 3
Extend your code so that:
When button A and B are pressed together the display shows a random image.
When button A and B are pressed together 10 times the NYAN music is played. The count is reset afterwards.
Hint
You will need to use the random library https://docs.micropython.org/en/latest/library/random.html
Solution
Solution is locked