Om Kamath
Published © GPL3+

Wireless Servo Control: Using Bluepad32 to Connect a Gamepad

Take Your Arduino Nano RP2040 Connect Projects to the Next Level with Wireless Servo Control via Bluepad32 and CircuitPython.

IntermediateProtip3 hours303
Wireless Servo Control: Using Bluepad32 to Connect a Gamepad

Things used in this project

Hardware components

Arduino Nano RP2040 Connect
Arduino Nano RP2040 Connect
×1
SG90 Micro-servo motor
SG90 Micro-servo motor
×1
AC/DC Power Supply, External Plug In
AC/DC Power Supply, External Plug In
×1

Story

Read more

Schematics

Wiring diagram

Code

Final code

Python
import time
import board
import busio
import pwmio
from adafruit_motor import servo
from digitalio import DigitalInOut
from bluepad32.bluepad32 import Bluepad32


# Callback that will be called once a gamepad is connected
def on_connect(gp):
    global gamepad  # pylint: disable=global-statement
    gamepad = gp
    print("on_connect: ", gp)
    # Change ligthbar to Green: Red, Green, Blue
    gp.set_lightbar_color((0x00, 0xFF, 0x00))


# Callback that will be called when a gamepad is disconnected
def on_disconnect(gp):
    global gamepad  # pylint: disable=global-statement
    gamepad = None
    print("on_disconnect: ", gp)

def map_range(value, in_min, in_max, out_min, out_max):
    return (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

# Connected gamepad
gamepad = None

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.CS1)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

spi = busio.SPI(board.SCK1, board.MOSI1, board.MISO1)
bp32 = Bluepad32(spi, esp32_cs, esp32_ready, esp32_reset, debug=0)
bp32.setup_callbacks(on_connect, on_disconnect)

# Should display "Bluepad32 for Airlift vXXX"
print("Firmware version:", bp32.firmware_version)


# Create a PWMOut object on the board pin connected to the servo
pwm = pwmio.PWMOut(board.A2, duty_cycle=2 ** 15, frequency=50)

# Create a Servo object using the PWMOut object
my_servo = servo.Servo(pwm)

# Define the minimum and maximum input values
min_input = 511
max_input = -512

# Define the minimum and maximum output values
min_output = 0
max_output = 180



while True:
    # Fetches data from Bluepad32 firmware, triggers callbaks, and more.
    # Must be called once per frame.
    bp32.update()

    if gamepad is None:
        continue
    
    print(gamepad)
    # Read the input value from the gamepad
    input_value = getattr(gamepad,'axis_x')
    # Map the input value to the output value range
    output_value = map_range(input_value, min_input, max_input, min_output, max_output)
    print(output_value)
    # Set the angle of the servo to the mapped output value
    my_servo.angle = output_value

    time.sleep(0.032)

Credits

Om Kamath

Om Kamath

1 project • 0 followers

Comments