I’m trying to interpret joystick inputs on a PC using PyGame and send those inputs over serial using PySerial. I’ve got code that sends the inputs whenever the joystick moves, but unfortunately I’d like to keep 8 bits for the sake of precision - so how do I let the Arduino know when the data is starting and ending? Should I do something like reserve ‘00’ and ‘FF’ in the Python code? I’m scratching my head over here…
Python code (arduino code is rather trivial at the moment):
import serial
import pygame
# allow multiple joysticks
joy = []
# Arduino USB port address (COM3)
usbport = 2
# define usb serial connection to Arduino
ser = serial.Serial(usbport, 115200)
# handle joystick event
def handleJoyEvent(e):
if e.type == pygame.JOYAXISMOTION:
axis = "unknown"
if (e.dict['axis'] == 0):
axis = "X"
if (e.dict['axis'] == 1):
axis = "Y"
if (e.dict['axis'] == 2):
axis = "Throttle"
if (e.dict['axis'] == 3):
axis = "Z"
if (axis != "unknown"):
str = "Axis: %s; Value: %f" % (axis, e.dict['value'])
# uncomment to debug
#output(str, e.dict['joy'])
# Send Servo Data
if (axis == "X"):
pos = e.dict['value']
# convert joystick position to servo increment, 0-180
move = round(pos * 90, 0)
if (move < 0):
servoX = int(90 - abs(move))
else:
servoX = int(move + 90)
# convert position to ASCII character
servoPositionX = chr(servoX)
# Send X pos to Arduino
ser.write(servoPositionX)
# uncomment to debug
print "X:",servoX
if (axis == "Y"):
pos = e.dict['value']
# convert joystick position to servo increment, 0-180
move = round(pos * 90, 0)
if (move < 0):
servoY = int(90 - abs(move))
else:
servoY = int(move + 90)
# convert position to ASCII character
servoPositionY = chr(servoY)
#send to Arduino over serial connection
ser.write(servoPositionY)
# uncomment to debug
print "Y:",servoY
if (axis == "Throttle"):
pos = e.dict['value']
move = round((pos+1)*128, 0)
if (move > 255):
move = 255
if (move < 0):
servoT = int(abs(move))
else:
servoT = int(move)
# convert joystick position to servo increment, 0-180
# convert position to ASCII character
servoPositionT = chr(servoT)
#send to Arduino over serial connection
ser.write(servoPositionT)
# uncomment to debug
print "T:",servoT
elif e.type == pygame.JOYBUTTONDOWN:
str = "Button: %d" % (e.dict['button'])
# uncomment to debug
#output(str, e.dict['joy'])
# Button 0 (trigger) to quit
if (e.dict['button'] == 0):
print "Bye!\n"
ser.close()
quit()
else:
pass