I’m trying to get a Dualshock 4 controller to move serial bus servos. A Python program is reading the inputs from the controller and sending them via serial communication to an ESP32 chip running an Arduino program that’s driving the servos.
How can I have a servo run continuously when I push a joystick in one direction, then stop when the joystick’s position returns to zero? The Arduino code works, I have the python program sending single digits as strings, which the Arduino code converts to integers and based on the number will drive a servo in forward, reverse, or stop.
I’m using Pygame to read the controller inputs and while it’s easy to have it constantly spam a number depending on the position of the joystick, I want to only send a number once after I move the stick away from zero, then once again when it returns to zero:
import serial
import time
import pygame as pg
pg.init()
pg.joystick.init()
j = pg.joystick.Joystick(0)
j.init()
ser = serial.Serial("COM5", 115200)
time.sleep(2)
def serWrite(a):
b = str(a)
ser.write(b.encode())
print(b)
done = False
while True:
pg.event.pump()
y = j.get_axis(0)
y = round (y,1)
print(y)
print(done)
while not done:
if y > 0.5:
serWrite(2)
done = True
print(done)
elif y < -0.5:
serWrite(3)
done = True
print(done)
#print("waiting")
if y == 0 and done == True:
serWrite(1)
done = False
print(done)
It works but only for the first loop. As soon as it gets to the end of the pump event where it checks for the current axis value, the loop stops. If I move the joystick before it gets to that point it works as intended and only writes one value, then another when I let go of the joystick. However after that it refuses to move past that first print(done)
and re-enter the nested while loop.
The solutions I’ve tried had it do the same thing but with different syntax. I’m also not sure if this will work with two joysticks at the same time to control two different servos.
calupino is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.