DEV Community

dan
dan

Posted on

1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay