bbcmicrobit / micropython

Port of MicroPython for the BBC micro:bit
https://microbit-micropython.readthedocs.io
Other
609 stars 286 forks source link

how to do a interupt with python #502

Open yonghuming opened 6 years ago

yonghuming commented 6 years ago
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

deshipu commented 6 years ago

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.

rhubarbdog commented 6 years ago

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.