ESP32-BLE-Gamepad

repository·master·Indexed 23 days ago

https://github.com/lemmingdev/esp32-ble-gamepad

A Bluetooth LE Gamepad library for the ESP32 using the NimBLE stack. It enables the creation of a configurable HID gamepad supporting up to 128 buttons, axes, sliders, hats, and simulation controls. Compatible with ESP32, ESP32-C3, and ESP32-S3 series.

Tokens
2.3K
Snippets
3
Records
12
Agent score
32%

What's inside esp32-ble-gamepad

  1. Configure simulation controls and special buttons

    master

    The library supports simulation controls and special function buttons, but they are disabled by default.

    Simulation Controls:

    • rudder, throttle, accelerator, brake, steering.

    Special Buttons:

    • start, select, menu, home, back, volume up, volume down, volume mute.

    To use these, you must configure the HID descriptor using a BleGamepadConfig instance passed to bleGamepad.begin(config).

  2. Android compatibility notes for gamepads

    master

    Android OS maps buttons and axes differently than Windows. When designing for Android, consider the following:

    1. Analog Triggers: Android maps standard left/right trigger axes to BRAKE and GAS simulation controls. To ensure triggers work, enable the Accelerator and Brake simulation controls.
    2. Right Thumbstick: On Windows, the right thumbstick is typically z, rz. On Android, it may be z, rx.
      • Instead of setRightThumb(z, rz), use setZ() and setRX() separately, or use setRightThumbAndroid(z, rx).
  3. Change the device display name on Windows

    master

    If the device name appears as a generic string (e.g., '8 axis 16 button device with hat switch') in Windows testing software, you can change it via the Windows Registry Editor.

    Steps:

    1. Open regedit.exe with user privileges (not administrator).
    2. Navigate to: HKEY_CURRENT_USER\System\CurrentControlSet\Control\MediaProperties\PrivateProperties\Joystick\OEM
    3. Locate the subfolder for your device. The keys follow the pattern: VID -hex number- &PID -hex number- .
      • The default hardware ID for this project is VID_E502&PID_BBAB.
    4. Double-click the OEMName value.
    5. Enter your desired custom display name and press Enter.

    Note: This is a Windows-specific workaround.

  4. Install ESP32-BLE-Gamepad

    master

    Follow these steps to set up the library in the Arduino IDE:

    1. Prerequisite: Ensure you can use the ESP32 with the Arduino IDE.
    2. Download Library: Download the latest release from the releases page.
    3. Add to Arduino IDE: Go to Sketch -> Include Library -> Add .ZIP Library... and select the downloaded file.
    4. Install NimBLE dependency: Go to Tools -> Manage Libraries..., filter for NimBLE-Arduino by h2zero, and install it. This library is required for efficient Bluetooth operation.
  5. Improve connection stability and latency

    master

    To address slow, inconsistent, or high-latency connections:

    For Connection Stability:

    • TX Power: Try setting a stronger TX power level (up to 9). This can be configured in the CharacteristicsConfiguration.ino example.
    • Updates: Ensure both the ESP32-BLE-Gamepad and NimBLE-Arduino libraries are updated to the latest versions.

    For High Latency/Unresponsiveness:

    • Loop Optimization: Optimize your code to reduce delays in the loop that handles gamepad inputs.
    • Avoid Delays: Minimize the use of delay() functions, as they introduce latency.
    • Connection Interval: Ensure the BLE connection interval is set appropriately for low-latency communication.
  6. Resolve configuration changes not taking effect

    master

    If you modify the BLE Gamepad configuration (such as device name, device features, button count, axes count, or button assignments) and the changes are not reflected on the host device, it is likely because the host operating system has cached the previous Bluetooth device characteristics.

    Solution:

    1. Unpair the device: On your host (PC, mobile, or console), go to Bluetooth settings, find the ESP32 device, and select "Remove," "Delete," "Unpair," or "Forget."
    2. Restart: Restart both the ESP32 and the host device.
    3. Re-pair: Pair the devices again to force the host to fetch the updated configuration.
    4. Verify Code: Ensure you are actually passing your custom configuration object to the begin method:
      bleGamepad.begin(&bleGamepadConfig);
    bleGamepad.begin(&bleGamepadConfig);
  7. Troubleshoot connection problems and visibility

    master

    If the ESP32 does not appear on your PC or is only visible on mobile devices, check the following:

    • Hardware Compatibility: Note that the ESP32-S2 Series has no Bluetooth. The ESP32, ESP32-C3, and ESP32-S3 series are supported.
    • Drivers: Ensure your PC's Bluetooth drivers are up to date.
    • Pairing State: Ensure the ESP32 is not already paired with another device. You can use the methods demonstrated in the ForcePairingMode.ino example to handle this.
    • Proximity & Power: Ensure the ESP32 is close to the host and has a stable power supply to prevent signal interference or performance drops.
  8. Troubleshoot GPIO pin functionality

    master

    If certain GPIO pins are not working for button inputs or analog readings:

    • Pinout Verification: Consult the official Espressif pinout documentation for your specific chip to ensure the selected pins support the desired functions.
    • Avoid Reserved Pins: Do not use pins that are reserved or have dual functions that might interfere with input readings.
    • Independent Testing: Test the pins independently before integrating them into your full gamepad setup.

    Reference Pinouts:

  9. Basic usage example

    master

    This example demonstrates how to initialize the gamepad, press buttons, move axes to maximum, and set a hat switch position.

    #include <Arduino.h>
    #include <BleGamepad.h>
    
    BleGamepad bleGamepad;
    
    void setup()
    {
        Serial.begin(115200);
        Serial.println("Starting BLE work!");
        bleGamepad.begin();
    }
    
    void loop()
    {
        if (bleGamepad.isConnected())
        {
            Serial.println("Press buttons 5, 16 and start. Move all enabled axes to max. Set DPAD (hat 1) to down right.");
            bleGamepad.press(BUTTON_5);
            bleGamepad.press(BUTTON_16);
            bleGamepad.pressStart();
            bleGamepad.setAxes(32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767);       //(X, Y, Z, RX, RY, RZ)
            bleGamepad.setHat1(HAT_DOWN_RIGHT);
            delay(500);
    
            Serial.println("Release button 5 and start. Move all axes to min. Set DPAD (hat 1) to centred.");
            bleGamepad.release(BUTTON_5);
            bleGamepad.releaseStart();
            bleGamepad.setHat1(HAT_CENTERED);
            bleGamepad.setAxes(0, 0, 0, 0, 0, 0, 0, 0);           //(X, Y, Z, RX, RY, RZ)
            delay(500);
        }
    }
  10. Control axes and sliders

    master

    The library provides methods to set axes and sliders. Note that since version 5, the default range for axes is 0 (minimum) to 32767 (maximum) to ensure compatibility with non-Windows OS and web testers.

    Setting all axes at once:

    • bleGamepad.setAxes(x, y, z, rx, ry, rz, slider1, slider2)
    • Order: (x, y, z, rx, ry, rz)

    Alternative HID order:

    • bleGamepad.setHIDAxes(x, y, z, rz, rx, ry, slider1, slider2)
    • Order: (x, y, z, rz, rx, ry)

    Individual Axis Control: Axes and sliders can also be set independently (e.g., setZ, setRX, etc.).

  11. Initialize BleGamepad with custom device info

    master

    You can initialize the BleGamepad instance with a custom device name, manufacturer, and initial battery level.

    Constructor Signature: BleGamepad(const char* deviceName, const char* manufacturer, uint8_t initialBatteryLevel)

    Defaults:

    • Name: ESP32 BLE Gamepad
    • Manufacturer: Espressif
    • Battery: 100%

    Example of setting battery level during operation: bleGamepad.setBatteryLevel(80); (Update is sent on the next gamepad update unless auto-reporting is disabled).

    BleGamepad bleGamepad("Bluetooth Device Name", "Bluetooth Device Manufacturer", 100);
  12. Control buttons and hats

    master

    The library supports up to 128 buttons and multiple hat switches (D-pads).

    Buttons:

    • Use bleGamepad.press(BUTTON_N) and bleGamepad.release(BUTTON_N) where N is 1 to 128 (default is 16).
    • Special buttons like start and select are enabled by default. Use bleGamepad.pressStart() / bleGamepad.releaseStart().

    Hat Switches (D-pads):

    • Use bleGamepad.setHat1(POSITION).
    • Valid positions include: DPAD_CENTERED, DPAD_UP, DPAD_UP_RIGHT, DPAD_RIGHT, DPAD_DOWN_RIGHT, DPAD_DOWN, DPAD_DOWN_LEFT, DPAD_LEFT, DPAD_UP_LEFT (or HAT_ prefix equivalents).