我与两个通过操纵杆控制的两轮机器人一起工作。现在,当我编写前进,后退和转弯的条件时,就会有一个永久的动作。我创建了else条件,以便释放操纵杆的轴时,机器人不会移动,但是在此条件下会出现延迟。当机器人移动时,它可以在一秒钟后停止,尽管我没有松开轴,但它可以在最大值处停止。请告诉我释放轴时如何编写停止机器人的最佳条件。 (键盘控制需要以防万一)
import socket
import pygame
import time
import pygame.joystick
pygame.init()
pygame.display.set_mode((640, 480))
rc_socket = socket.socket()
rc_socket_2 = socket.socket()
try:
rc_socket.connect(('192.168.1.102', 1234)) # connect to robot
rc_socket_2.connect(("192.168.1.101",1234))
except socket.error:
print("could not connect to socket")
joystick_count = pygame.joystick.get_count()
pygame.joystick.init()
joystick = pygame.joystick.Joystick(0)
joystick.init()
joystick_2 = pygame.joystick.Joystick(1)
joystick_2.init()
axes = joystick.get_numaxes()
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.JOYAXISMOTION:
joy = event.joy
axis = event.axis
value = event.value
if joy == 0:
if axis == 1:
if abs(value) >= 0.2:
u1 = u2 = -value
rc_socket.send('({},{})\n'.format(u1, u2).encode())
# print('({},{})\n'.format(u1, u2))
print(value)
elif axis == 3:
if abs(value) >= 0.2:
u1 = -value
u2 = value
rc_socket.send('({},{})\n'.format(u1, u2).encode())
# print('({},{})\n'.format(u1, u2))
print(value)
elif axis == 2:
if value >= 0:
u1 = 0
u2 = abs(value)
rc_socket.send('({},{})\n'.format(u1, u2).encode())
print(value)
else:
u1 = u2 = 0
rc_socket.send('({},{})\n'.format(u1, u2).encode())
# print('({},{})\n'.format(u1, u2))
#print("{} -> sending (0,0)".format(value))
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
u1 = -1.0
u2 = 1.0
print("turn left: ({},{})".format(u1, u2))
elif event.key == pygame.K_RIGHT:
u1 = 1.0
u2 = -1.0
print("turn right: ({},{})".format(u1, u2))
elif event.key == pygame.K_UP:
u1 = 1.0
u2 = 1.0
print("forward: ({},{})".format(u1, u2))
elif event.key == pygame.K_DOWN:
u1 = -1.0
u2 = -1.0
print("forward: ({},{})".format(u1, u2))
rc_socket_2.send('({},{})\n'.format(u1, u2).encode())
elif event.type == pygame.KEYUP:
u1 = 0
u2 = 0
print("key released, resetting: ({},{})".format(u1, u2))
rc_socket_2.send('({},{})\n'.format(u1, u2).encode())