Detect one certain button in the remote is realeased #961
Unanswered
JobadSayas
asked this question in
Q&A
Replies: 2 comments
-
This is how I like to do it. It uses a generator function to create a "stream" of events. from pybricks.pupdevices import Remote, Motor
from pybricks.parameters import Button, Port
SPEED = 400
motor = Motor(Port.A)
remote = Remote()
def button_events(buttons):
"""
Yields a tuple of a ``Button`` and a ``bool`` each time a button
in *buttons* changes state. When the button is pressed, the second
value in the tuple is ``True`` and when the button is released,
the second value in the tuple is ``False.
Args
buttons:
A list of buttons we are interested in receiving events from.
Buttons not in the list will be ignored.
"""
was_pressed = ()
while True:
pressed = remote.buttons.pressed()
for b in buttons:
if b in pressed and b not in was_pressed:
# if a button was previously not pressed
# but is pressed now, emit a "pressed"
# event
yield b, True
elif b not in pressed and b in was_pressed:
# if a button was previously pressed
# and is not pressed now, emit a "released"
# event
yield b, False
was_pressed = pressed
for button, is_pressed in button_events([Button.LEFT_PLUS, Button.LEFT_MINUS]):
if button == Button.LEFT_PLUS:
if is_pressed:
motor.run(SPEED)
else:
motor.stop()
elif button == Button.LEFT_MINUS:
if is_pressed:
motor.run(-SPEED)
else:
motor.stop() |
Beta Was this translation helpful? Give feedback.
0 replies
-
Wow! this works absolutely awesome! I would never come to this solution, you know them all man!, thanks! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi, I am trying to active trigger an action when the button is pressed, but to stop it when I stop pressing that button.
In this case is action is running the motors A & B while pressing the button, then when releasing the key stop it. I am trying to do it by using a variable to move or stop the motors because I want to have also the ability to move the motors not only by holding the buttons in the traditional way, but because I want to have the ability to move the motors in other ways like running for specific time, etc. Basically having manual driving mode (holding the buttons) or self driving.
I have tried using something like this, but doesn't work:
Beta Was this translation helpful? Give feedback.
All reactions