# Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255)
# This is a simple class that will help us print to the screen # It has nothing to do with the joysticks, just outputting the # information. class TextPrint: def __init__(self): self.reset() self.font = pygame.font.Font(None, 20)
# Set the width and height of the screen [width,height] size = [500, 700] screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
# Loop until the user clicks the close button. done = False
# Used to manage how fast the screen updates clock = pygame.time.Clock()
# Initialize the joysticks pygame.joystick.init()
# Get ready to print textPrint = TextPrint()
# -------- Main Program Loop ----------- while done == False: # EVENT PROCESSING STEP for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop
# Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION if event.type == pygame.JOYBUTTONDOWN: print("Joystick button pressed.") if event.type == pygame.JOYBUTTONUP: print("Joystick button released.")
# DRAWING STEP # First, clear the screen to white. Don't put other drawing commands # above this, or they will be erased with this command. screen.fill(WHITE) textPrint.reset()
# Get count of joysticks joystick_count = pygame.joystick.get_count()
textPrint.print(screen, "Number of joysticks: {}".format(joystick_count)) textPrint.indent()
# For each joystick: for i in range(joystick_count): joystick = pygame.joystick.Joystick(i) joystick.init()
# Get the name from the OS for the controller/joystick name = joystick.get_name() textPrint.print(screen, "Joystick name: {}".format(name))
# Usually axis run in pairs, up/down for one, and left/right for # the other. axes = joystick.get_numaxes() textPrint.print(screen, "Number of axes: {}".format(axes)) textPrint.indent()
for i in range(axes): axis = joystick.get_axis(i) textPrint.print(screen, "Axis {} value: {:>6.3f}".format(i, axis)) textPrint.unindent()
buttons = joystick.get_numbuttons() textPrint.print(screen, "Number of buttons: {}".format(buttons)) textPrint.indent()
for i in range(buttons): button = joystick.get_button(i) textPrint.print(screen, "Button {:>2} value: {}".format(i, button)) textPrint.unindent()
# Hat switch. All or nothing for direction, not like joysticks. # Value comes back in an array. hats = joystick.get_numhats() textPrint.print(screen, "Number of hats: {}".format(hats)) textPrint.indent()
for i in range(hats): hat = joystick.get_hat(i) textPrint.print(screen, "Hat {} value: {}".format(i, str(hat))) textPrint.unindent()
textPrint.unindent()
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
# Go ahead and update the screen with what we've drawn. pygame.display.flip()
# Limit to 20 frames per second clock.tick(20)
# Close the window and quit. # If you forget this line, the program will 'hang' # on exit if running from IDLE. pygame.quit()
上位机远程控制
手柄数据获取
使用左侧摇杆作为方向控制,左侧按键作为倒车,右侧为油门(优先级低于左侧)
注意while循环里面的for event in pygame.event.get():部分不可删除,否则无法读取。
while 1: for event in pygame.event.get(): # User did something # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION if event.type == pygame.JOYBUTTONDOWN: print("Joystick button pressed.") if event.type == pygame.JOYBUTTONUP: print("Joystick button released.") joystick = pygame.joystick.Joystick(0) joystick.init()
# direction from -1 ~ 1, returns to 0 automatically axis0 = joystick.get_axis(0) if axis0 > 0.1 or axis0 < -0.1: direction = axis0 else: direction = 0 print(direction) # speed from -1 to 1, returns to -1 automatically speed = joystick.get_axis(4) print(speed)
def recv_size(sock, count): buf = '' while count: newbuf = sock.recv(count) if not newbuf: return None buf += newbuf count -= len(newbuf) return buf
def web(): global direction global run tcp_server_socket = socket(AF_INET, SOCK_STREAM) tcp_server_socket.bind(address) tcp_server_socket.listen(8) client_socket, client_addr = tcp_server_socket.accept() while 1: try: time.sleep(0.1) data = {"direction": direction, "run": run} client_socket.send(json.dumps(data).encode('utf-8')) except: client_socket, client_addr = tcp_server_socket.accept()
_thread.start_new_thread(web, ())
while 1: for event in pygame.event.get(): # User did something # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION if event.type == pygame.JOYBUTTONDOWN: print("Joystick button pressed.") if event.type == pygame.JOYBUTTONUP: print("Joystick button released.") joystick = pygame.joystick.Joystick(0) joystick.init()
# direction from -1 ~ 1, returns to 0 automatically axis0 = joystick.get_axis(0) if axis0 > 0.1 or axis0 < -0.1: direction = axis0 else: direction = 0 # speed from -1 to 1, returns to -1 automatically speed = joystick.get_axis(5) + 1 # 0~2 speed_back = -1 - joystick.get_axis(4) # -2~0 if speed_back == 0: run = speed else: run = speed_back print("direction", direction, "run", run, 'speed', speed, 'speed_back', speed_back) clock.tick(10)
import _thread import re import time from socket import * import json
direction = 0 speed = -1 server = ("127.0.0.1", 7788)
def get_data(): global direction global speed s = socket(AF_INET, SOCK_STREAM) s.connect(server) while 1: try: rec = s.recv(1024).decode("utf-8") data = json.loads(rec) direction = float(data['direction']) speed = float(data['speed']) print("direction", direction, "speed", speed) except: s = socket(AF_INET, SOCK_STREAM) s.connect(server)
_thread.start_new_thread(get_data, ()) while 1: time.sleep(10)
#!/usr/bin/env python3 import rospy from geometry_msgs.msg import Twist import numpy as np import _thread import time from socket import * import json
control_speed = 1500 # 500-1499倒车/1500停车/1501-2500前进 turn_mid = 90 # 舵机中值是90 direction = 0 run = 0 server = ("triority.cc", 7788)
def get_data(): global direction global run s = socket(AF_INET, SOCK_STREAM) s.connect(server) while 1: try: rec = s.recv(1024).decode("utf-8") data = json.loads(rec) direction = float(data['direction']) run = float(data['run']) print("direction", direction, "run", run) except: s = socket(AF_INET, SOCK_STREAM) s.connect(server)
String comStr = ""; long comInt=0; long speed=2000; long dir=90;
void setup() { // put your setup code here, to run once: Serial.begin(9600); while(Serial.read()>=0){} // clear serial port's buffer myServo.attach(9); // attach myServo to GPIO_09 myServo.write(90); pwm.attach(10);
void loop() { // put your main code here, to run repeatedly: if (Serial.available() > 0){ // listen the Serial port, run the code when something catched.. delay(30); comStr = Serial.readString(); comInt = comStr.toInt(); comInt = constrain(comInt, 1000060, 2000120); Serial.println(comStr); Serial.println(comInt); speed = comInt/1000; speed = constrain(speed, 1000, 2000); Serial.println(speed); dir = comInt - speed*1000; dir = constrain(dir, 60, 120); Serial.println(dir);
ports_list = list(serial.tools.list_ports.comports()) if len(ports_list) <= 0: print("无串口设备") else: for comport in ports_list: print(list(comport)[0], list(comport)[1])
ser = serial.Serial('/dev/ttyUSB0',9600,timeout=1) ser.write('1500090'.encode())
void loop(){ Serial.println("connecting to server"); if (client.connect(serverIP, serverPort)){ Serial.println("connected"); while (client.connected() || client.available()){ if (client.available()){ String d = client.readStringUntil('d'); Serial.println(d); dir = d.toInt(); String r = client.readStringUntil('r'); run = r.toInt(); Serial.println(r);
def recv_size(sock, count): buf = '' while count: newbuf = sock.recv(count) if not newbuf: return None buf += newbuf count -= len(newbuf) return buf
def web(): global direction global run tcp_server_socket = socket(AF_INET, SOCK_STREAM) tcp_server_socket.bind(address) tcp_server_socket.listen(8) client_socket, client_addr = tcp_server_socket.accept() while 1: try: time.sleep(0.03) dir = 90 - int(direction*30) if run >= 0: r = 1500 + int(250*run) else: r = 1100 client_socket.send((str(dir)+'d'+str(r)+'r').encode('utf-8')) except: client_socket, client_addr = tcp_server_socket.accept()
_thread.start_new_thread(web, ())
while 1: for event in pygame.event.get(): # User did something # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION if event.type == pygame.JOYBUTTONDOWN: print("Joystick button pressed.") if event.type == pygame.JOYBUTTONUP: print("Joystick button released.") joystick = pygame.joystick.Joystick(0) joystick.init()
# direction from -1 ~ 1, returns to 0 automatically axis0 = joystick.get_axis(0) if axis0 > 0.1 or axis0 < -0.1: direction = axis0 else: direction = 0 # speed from -1 to 1, returns to -1 automatically speed = joystick.get_axis(5) + 1 # 0~2 speed_back = -1 - joystick.get_axis(4) # -2~0 if speed_back == 0: run = speed else: run = speed_back print("direction", direction, "run", run, 'speed', speed, 'speed_back', speed_back) clock.tick(10)
The domain name of this website has been changed to triority.cc(Using CDN via cloudflare, recommended) / www.triority.cc(Connecting directly, works better in Chinese mainland). Please contact me if you have any questions.