hi Richard,
I'm not sure that interrupts necessarily make this easier.
The key thing though is that while the micro:bit is sleeping, it can't be doing anything else. So it helps to imagine how the sleep function itself works:
Code: Select all
def sleep(delay_ms):
t = running_time()
while running_time() < t + delay_ms:
pass
You can kind of implement your own version of sleep into the main loop of your program. In this case we figure out when the next letter should be shown.
Code: Select all
import microbit
marcelList = ["M", "A", "R", "C", "E", "L"]
maxIndex = 5
next_letter_time = 0
disp = False
letter_delay = 1000
index = 0
while True:
if microbit.button_a.is_pressed():
disp = True
next_letter_time = microbit.running_time() + letter_delay
if microbit.button_b.is_pressed():
disp = False
next_letter_time = 0
if disp and microbit.running_time() > next_letter_time:
microbit.display.show(str(marcelList[index]))
index = index + 1
if index > maxIndex:
index = 0
next_letter_time = microbit.running_time() + letter_delay
I genererally prefer to use was_pressed unless there's a specific reason to use is_pressed. The letters can be a string too, instead of a list. So here's a simplified version -- you also kind of don't need the "disp" variable anymore because next_letter_time != 0 implies disp = True.
Code: Select all
import microbit
marcel = "MARCEL"
next_letter_time = 0
letter_delay = 1000
index = 0
while True:
if microbit.button_a.was_pressed():
next_letter_time = microbit.running_time() + letter_delay
if microbit.button_b.was_pressed():
next_letter_time = 0
if next_letter_time > 0 and microbit.running_time() > next_letter_time:
microbit.display.show(marcel[index])
index = (index + 1) % len(marcel)
next_letter_time = microbit.running_time() + letter_delay
You might want to display.clear() when b is pressed too?
FYI I wrote this blog post about this exact topic a while back for my previous employer -- there might be some useful bits.
https://medium.com/groklearning/become- ... b8b4e2d747 You might find their micro:bit simulator useful too (which you can access for free by starting the micro:bit course and going to any problem --
https://groklearning.com/microbit/), I used it to test the above code.