micropython
micropython copied to clipboard
how to do a interupt with python
from microbit import *
img = Image()
mode = 'sos' # light mode and flash mode
while True:
if button_a.is_pressed():
mode = 'flash'
if mode == 'flash':
img.fill(0)
display.show(img)
sleep(40)
img.fill(9)
display.show(img)
sleep(40)
if mode == 'light':
img.fill(9)
display.show(img)
if mode == 'sos':
# s
img.fill(9)
display.show(img)
sleep(500)
display.clear()
sleep(500)
display.show(img)
sleep(500)
display.clear()
sleep(500)
display.show(img)
sleep(500)
display.clear()
sleep(500)
# 0
display.show(img)
sleep(1500)
display.clear()
sleep(1500)
display.show(img)
sleep(1500)
display.clear()
sleep(1500)
display.show(img)
sleep(1500)
display.clear()
sleep(1500)
# s
img.fill(9)
display.show(img)
sleep(500)
display.clear()
sleep(500)
display.show(img)
sleep(500)
display.clear()
sleep(500)
display.show(img)
sleep(500)
display.clear()
sleep(500)
hi, i want to change mode when press buttons, but the sleep prevent detect press event, i want to change mode when press button
The solution is to not use sleep (or use only very short sleeps), but instead completely change the organization of your code to keep track of the current state and the time left to do the next action.
have you tried using button_a.get_presses()
this returns the number of times a button has been pressed since last called. if 0 is returned the button has not been pressed.