bbcmicrobit / bbcmicrobit/micropython

Docs - Add discussion on how to detect "simultaneous" press on button a and b

Open
#470 5 comments 0 reactions 0 assignees View on GitHub
Dominant language
C
Stars
646
Forks
290
PR merge metrics
No merged PRs in 30d

Description

**Problem:** In an event loop, detect whether button a and button b was pressed "at the same time", only button a was pressed or only button b was pressed.

First attempt.

```
while True:

if button_a.was_pressed() and button_b.was_pressed():
display.show(Image.HAPPY)
elif button_a.was_pressed():
display.show(Image.ARROW_W)
elif button_b.was_pressed():
display.show(Image.ARROW_E)
```

This fails for two reasons.

1) There is not enough time for a human user to press buttons a and b "at the same time", the event loop executes to fast.
2) If only button a is pressed, `button_a.was_pressed() and button_b.was_pressed()` evaluates to `False` but as a result of the call `button_a.was_pressed()` the next call to `button_a.was_pressed()` in the `elif` branch evaluates to `False`.

The below solution solves both of the above problems.

```
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)

```

Would be nice if a discussion about this with a working example could be added to the docs, here http://microbit-micropython.readthedocs.io/en/latest/tutorials/buttons.html or here http://microbit-micropython.readthedocs.io/en/latest/button.html#

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.