DEV Community

dan
dan

Posted on

Control a servo connected to a Raspberry Pi using an Xbox controller

https://github.com/dcs-ink/raspberry_servo_controller

raspberry_servo_controller

output4

Control a servo connected to a Raspberry Pi using an Xbox controller. Easy setup for testing.

Parts list:

  • raspberry pi 4
  • xbox controller
  • power bank
  • breadboard
  • 100 ยตF capacitor
  • servo
  • jumper wires

Diagram

wire_diagram

Instructions

  1. Prep Raspberry Pi (I used Raspberry OS Lite but I imagine most OS's should work)
  2. Install dependancies
   sudo apt-get install -y evtest evdev
Enter fullscreen mode Exit fullscreen mode
  1. Pair controller
   bluetoothctl
   scan on
   pair XX:XX:XX:XX:XX:XX
   trust XX:XX:XX:XX:XX:XX
   connect XX:XX:XX:XX:XX:XX
Enter fullscreen mode Exit fullscreen mode

Make note of the ID; eventX

  1. Look at controller output
   sudo evtest /dev/input/eventX
Enter fullscreen mode Exit fullscreen mode
  1. Create python script
   vim ServoController.py
Enter fullscreen mode Exit fullscreen mode

copy paste (be sure to change 'eventX' to your controller id

   import evdev
   import RPi.GPIO as GPIO
   import time

   GPIO.setmode(GPIO.BOARD)
   GPIO.setup(11,GPIO.OUT)
   servo = GPIO.PWM(11,50)
   servo.start(0)

   controllerInput = evdev.InputDevice("/dev/input/event0")

    for event in controllerInput.read_loop():
      if event.type == evdev.ecodes.EV_ABS:
        if event.code == evdev.ecodes.ABS_X:
          angle = 2 + (event.value / 6553.5)
          servo.ChangeDutyCycle(angle)
          print(angle)
Enter fullscreen mode Exit fullscreen mode
  1. Run script
   python3 ServoController.py
Enter fullscreen mode Exit fullscreen mode

Thanks to Berardinux for the code and guide! XboxController_Servo_RaspberryPi
https://youtu.be/3Z6Bf0uV7tc?si=rzX2nBYM4o1anVEc

Top comments (0)