Jump to content

Control servomotor from raspberry pi using a ps4 controler

Hello i have a servo motor that i wana control using a ps4 controler over bluethoot and i cant seam to find eny information on a servomotro and ps4 controler combined and i was wandfering if enybody can help i now how to read from ps4 controler and how to output a signal to servo motor from googleing but i dont know how to combine them (btw i am using python) pls help thx for your time

 

This is the code to read the value from the controler from -1 to 1 and 0 is idle or off in case of buttones

import pygame
from time import sleep
pygame.init()
controller = pygame.joystick.Joystick(0)
controller.init()
buttons = {'x':0,'o':0,'t':0,'s':0,
           'L1':0,'R1':0,'L2':0,'R2':0,
           'share':0,'options':0,
           'axis1':0.,'axis2':0.,'axis3':0.,'axis4':0.}
axiss=[0.,0.,0.,0.,0.,0.]
 
 
def getJS(name=''):
 
    global buttons
    # retrieve any events ...
    for event in pygame.event.get():                                # Analog Sticks
        if event.type == pygame.JOYAXISMOTION:
            axiss[event.axis] = round(event.value,2)
        elif event.type == pygame.JOYBUTTONDOWN:                    # When button pressed
            #print(event.dict, event.joy, event.button, 'PRESSED')
            for x,(key,val) in enumerate(buttons.items()):
                if x<10:
                    if controller.get_button(x):buttons[key]=1
        elif event.type == pygame.JOYBUTTONUP:                      # When button released
            #print(event.dict, event.joy, event.button, 'released')
            for x,(key,val) in enumerate(buttons.items()):
                if x<10:
                    if event.button ==x:buttons[key]=0
 
    # to remove element 2 since axis numbers are 0 1 3 4
    buttons['axis1'],buttons['axis2'] ,buttons['axis3'] ,buttons['axis4']  = [axiss[0],axiss[1],axiss[3],axiss[4]]
    if name == '':
        return buttons
    else:
        return buttons[name]
def main():
    print(getJS()) # To get all values
    sleep(0.05)
    #print(getJS('share')) # To get a single value
    #sleep(0.05)
 
 
if __name__ == '__main__':
  while True:
    main()

and this is an example code for servomotors control

GPIO.setmode(GPIO.BOARD)

GPIO.setup(03, GPIO.OUT)

pwm=GPIO.PWM(03, 50)
pwm.start(0)

def SetAngle(angle):
    duty = angle / 18 + 2
    GPIO.output(03, True)
    pwm.ChangeDutyCycle(duty)
    sleep(1)
    GPIO.output(03, False)
    pwm.ChangeDutyCycle(0)
#now i can set angle to a degree
SetAngle(90) 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×