Better way to Trigger A+B Buttons

Questions and discussion about running MicroPython on a micro:bit board.
Target audience: MicroPython users with a micro:bit.
Post Reply
windflower28
Posts: 5
Joined: Sat Aug 15, 2020 5:45 pm

Better way to Trigger A+B Buttons

Post by windflower28 » Sat Aug 15, 2020 6:21 pm

Hi, I am a newbie of both microbit and python language. I am stuck on how to trigger A+B buttons.
I am trying to write a war game with microbit, that use both button A, B and A+B. I try to set press A to move my ship (one pixel on broad) to the left, and press B move to the right. finally, press A+B to fire. But I don't know how to trigger A+B action in a better way. every time I press A+B, it comes out not fire, but the ship move to left or right. It is not easy to trigger A+B accurately.
My code is in the following, Please kindly advise how to improve it . Thanks

Code: Select all

from microbit import *

while True:
    if button_a.is_pressed() and button_b.is_pressed():
        fire.......
    elif button_a.is_pressed():
        ship move left.......
    elif button_b.is_pressed():
        ship move right.......
    sleep(100)


User avatar
rcolistete
Posts: 322
Joined: Thu Dec 31, 2015 3:12 pm
Location: Brazil
Contact:

Re: Better way to Trigger A+B Buttons

Post by rcolistete » Sat Aug 15, 2020 7:50 pm

See this GitHub issue #470 "Docs - Add discussion on how to detect "simultaneous" press on button a and b".

So this example works :

Code: Select all

from microbit import *

while True:
    # Solves issue 1
    sleep(50)  # How long sleep is "just enough"?
    
    # Solves issue 2
    (a, b) = (button_a.was_pressed(), button_b.was_pressed())
    
    if a and b:
        display.show(Image.HAPPY)
    elif a:
        display.show(Image.ARROW_W)
    elif b:
        display.show(Image.ARROW_E)
My "MicroPython Samples". My "MicroPython Firmwares" with many options (double precision, ulab, etc).

windflower28
Posts: 5
Joined: Sat Aug 15, 2020 5:45 pm

Re: Better way to Trigger A+B Buttons

Post by windflower28 » Sun Aug 16, 2020 10:28 am

It works. Thanks :D

Post Reply