[英]python pygame how to debounce a button?
so im building a pi based robot. 因此,我正在建立一个基于pi的机器人。 It uses a ps3 controller for input. 它使用ps3控制器进行输入。 When the X button is pressed, it takes a photo. 按下X按钮时,它会拍照。 For some reason, it takes around 5 shots at a time. 由于某种原因,一次拍摄约5张照片。 Is there a way to bounce the input so it only recognises one press? 有没有办法反弹输入,使其只能识别一次按动?
I'm assuming it's registering multiple presses each time... Part of the code is attached, but I must state most of it is used from piborg.org 我假设每次都在注册多台印刷机...部分代码已附加,但我必须声明大部分代码都来自piborg.org
joystick = pygame.joystick.Joystick(0)
button_take_picture = 14 # X button
while running:
# Get the latest events from the system
hadEvent = False
events = pygame.event.get()
# Handle each event individually
for event in events:
if event.type == pygame.QUIT:
# User exit
running = False
elif event.type == pygame.JOYBUTTONDOWN:
# A button on the joystick just got pushed down
hadEvent = True
elif event.type == pygame.JOYAXISMOTION:
# A joystick has been moved
hadEvent = True
if hadEvent:
if joystick.get_button(button_take_picture):
take_picture()
What seems to be happening is that the X button stays down for multiple frames. 似乎正在发生的事是X按钮停留了多个帧。 Some other events might happen during this time, causing a call to take_picture()
in your code for every frame. 在此期间可能还会发生其他一些事件,从而导致在每个帧中调用代码中的take_picture()
。 To fix this, you can either call take_picture()
only on JOYBUTTONUP
(when the button is released), or move the if joystick.get_button(button_take_picture)
part to inside the pygame.JOYBUTTONDOWN
section. 要解决此问题,您可以仅在JOYBUTTONUP
(释放按钮时take_picture()
上调用take_picture()
,或将if joystick.get_button(button_take_picture)
部分移至pygame.JOYBUTTONDOWN
部分内。
Alternatively, you could use another variable to indicate whether the picture was already taken, like this: 另外,您可以使用另一个变量来指示是否已拍摄照片,如下所示:
picture_was_taken = False
while running:
hadEvent = False
events = pygame.event.get()
for event in events:
...
if event.type == pygame.JOYBUTTONUP:
if not joystick.get_button(button_take_picture)
picture_was_taken = False
...
if hadEvent:
if joystick.get_button(button_take_picture) and not picture_was_taken:
take_picture()
picture_was_taken = True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.