我正在尝试制作一个简单的程序,当您按住“w”时,它会使用
forward ()
前进,但是当您松开时,它会使用 stop()
停止电机。目前,我只能让它在按下“w”时持续前进,只有在按下另一个键时才停止。
这是我的代码
#!/usr/bin/env python3
# so that script can be run from Brickman
import termios, tty, sys, time
from ev3dev.ev3 import *
# attach large motors to ports B and C, medium motor to port A
motor_left = LargeMotor('outA')
motor_right = LargeMotor('outD')
motor_a = MediumMotor('outC')
#==============================================
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setcbreak(fd)
ch = sys.stdin.read(1)
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
#==============================================
def fire():
motor_a.run_timed(time_sp=3000, speed_sp=600)
#==============================================
def forward():
motor_left.run_forever(speed_sp=1050)
motor_right.run_forever(speed_sp=1050)
#==============================================
def back():
motor_left.run_forever(speed_sp=-1050)
motor_right.run_forever(speed_sp=-1050)
#==============================================
def left():
motor_left.run_forever(speed_sp=-1050)
motor_right.run_forever(speed_sp=1050)
#==============================================
def right():
motor_left.run_forever(speed_sp=1050)
motor_right.run_forever(speed_sp=-1050)
#==============================================
def stop():
motor_left.run_forever(speed_sp=0)
motor_right.run_forever(speed_sp=0)
#==============================================
print("ready")
k = getch()
print(k)
if k == 'w':
forward()
if k == 's':
back()
if k == 'a':
left()
if k == 'd':
right()
if k == 'f':
fire()
if k == ' ':
stop()
if k == 'q':
stop()
exit()
有什么想法可以让 stop() 在松开 'w' 时运行吗?
您可以使用pygame的KEYUP和KEYDOWN功能。以下是使用 pygame 的代码片段:
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
finished = False
isKeyPressed = False
while not finished:
for event in pygame.event.get():
if isKeyPressed:
print "Key is currently pressed...Move forward!"
if event.type == pygame.QUIT:
finished = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
isKeyPressed = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
isKeyPressed = False
#Perform action (here) when 'w' is unpressed
pygame.display.flip()
clock.tick(60)
pygame.quit()