Bluepad32: drive your robot with a game controller

Bluepad32 is an open-source library by Ricardo Quesada. It makes the ESP32 a Bluetooth host, the same as a game console. You can connect a PlayStation, Xbox, Nintendo Switch, 8BitDo or Android controller directly to the ESP32. No phone and no app are necessary. Your sketch reads the sticks, triggers and buttons as numbers, so a robot, a camera slider or a game can use them. This page shows the values that Bluepad32 gives, the chips and controllers that operate together, and a complete robot sketch.

A black Sony DualShock 4 controller with two thumb sticks, a d-pad, four face buttons and a touchpad
A DualShock 4 (PS4) controller. Bluepad32 supports it on the classic ESP32.
Photo: Evan-Amos, public domain

Controller → Bluepad32 values

Keys (click the pad first): WASD left stick, IJKL right stick, Q/E triggers, Space = A, B = B

No real controller found. Connect a controller to this computer (USB or Bluetooth) and press a button on it.

Top view of the robot

Green wheel arrows turn forward and red arrows turn backward. The yellow arm is the servo: R2 (throttle) turns it one way and L2 (brake) turns it the other way. Hold B to stop the motors.

Real controller in the browser. The “Real controller” mode uses the browser Gamepad API (navigator.getGamepads() and the gamepadconnected event). The browser gives axes from −1 to 1 and triggers from 0 to 1. This page multiplies them by 512 and 1023 to show Bluepad32-like numbers. The browser and Bluepad32 use different drivers, so the button order, the stick calibration and the dead zone of a real controller can be different on the ESP32. Use this page to learn the ranges and to tune the mixing. Then make sure with the Serial Monitor on the ESP32. For privacy, browsers show a controller only after you press a button on it.

How Bluepad32 operates

The ESP32 is the host

A controller connects to a host (a console, a PC or a phone). Bluepad32 adds a full Bluetooth host stack (BTstack) and drivers for many controllers to the ESP32. The ESP32 scans, pairs and then receives the input reports. One ESP32 can connect up to 4 controllers (BP32_MAX_GAMEPADS) at the same time.

Callbacks and update()

You give Bluepad32 two functions. It calls the first when a controller connects and the second when it disconnects. Each function receives a ControllerPtr. Keep the pointer in an array. In loop(), call BP32.update(). It copies the newest data into each controller object, and then you read ctl->axisX(), ctl->a() and the other values.

One layout for all controllers

Bluepad32 converts each controller to one standard layout. The four face buttons use Xbox names by position: A is the bottom button (✕ on PlayStation), B is right, X is left and Y is top. So one sketch operates with a PS5, an Xbox or a Switch controller.

Use only one Bluetooth stack. Do not use the ESP32 BLE library, NimBLE-Arduino or BluetoothSerial in a Bluepad32 sketch, because Bluepad32 replaces the Bluetooth stack of the core. Wi-Fi can operate at the same time, but the two radios share one antenna, so the controller latency can increase.

Which ESP32 chip to use

Most game controllers use Bluetooth Classic (BR/EDR). Only the original ESP32 has Bluetooth Classic. The newer chips have only Bluetooth Low Energy (BLE), so they operate only with BLE controllers.

ChipBluetoothControllersArduino IDE board package
ESP32 (ESP32-WROOM-32, ESP32-WROVER, most DevKits)Classic + BLEAll PS3, PS4, PS5, Switch, Wii, 8BitDo, Xbox, Steam and othersYes
ESP32-S3BLE onlyBLE only Xbox (firmware 5.x), Steam, Stadia, some Android pads, BLE mice and keyboardsYes For serial output, read issue #65
ESP32-C3BLE onlyBLE only Same as ESP32-S3Yes
ESP32-C6, ESP32-H2, ESP32-C5BLE onlyBLE onlyNo Use the ESP-IDF template (Bluepad32 4.2 or newer)
ESP32-S2NoneNoneNo
For a robot class, buy classic ESP32 DevKits. With a classic ESP32, each student can use the controller that they already have.

Controllers and pairing

Upload a Bluepad32 sketch first. The ESP32 scans for controllers all the time. Then put the controller in pairing mode. A controller that paired before reconnects when you push its home button.

ControllerProtocolPairing procedure
DualSense (PS5), DualSense EdgeClassicHold Create. Push PS until the light bar blinks.
DualShock 4 (PS4)ClassicHold Share. Push PS until the light bar flashes.
DualShock 3 (PS3)ClassicThe DS3 has no pairing mode. Write the Bluetooth address of the ESP32 into the controller through USB (see below). Then push PS.
Xbox Wireless, model 1914 (with Share button)BLEUpdate the controller firmware to 5.15 or newer (Xbox Accessories app). Turn the controller on. Hold the Pair button for 3 seconds.
Xbox One S, model 1708BLE (firmware 5.x) or Classic (3.x, 4.x)Same as model 1914. Older Xbox One controllers without Bluetooth do not operate.
Switch Pro, Joy-Con (Switch 1)ClassicHold the small Sync button until the player LEDs move. Each Joy-Con is a separate controller.
Switch 2 Pro, Switch 2 Joy-ConBLEHold Sync until the LEDs flash. These need a new Bluepad32 version (ESP-IDF template). The Arduino IDE package 4.1.0 is older.
Wii Remote, Wii U ProClassicPush the red Sync button.
8BitDo controllersClassicStart the controller in Switch, Android (D-input) or Windows (X-input) mode. Hold the pair button. The mode buttons are different for each model, so read the 8BitDo manual.
Steam ControllerBLEInstall the Steam “Bluetooth” firmware first. Then push Y + Steam.
Android gamepadsClassic or BLEUse the pairing procedure of the manual. On S3/C3 chips, only BLE models operate.
Bluetooth mice and keyboardsClassic or BLEPut the device in pairing mode. Use isMouse() or isKeyboard() to find the device type in your sketch.

PS3 controller: write the ESP32 address

  1. Read the address of the ESP32.Upload a Bluepad32 sketch. Open the Serial Monitor at 115200 baud. Find the Bluetooth address in the boot messages, for example CC:50:E3:AF:E2:96. You can also print BP32.localBdAddress().
  2. Connect the DS3 to your computer with USB.
  3. Write the address into the DS3.The Bluepad32 docs use sixaxispairer from the Bluepad32 tools folder: sudo ./sixaxispairer CC:50:E3:AF:E2:96. On Windows, the older SixaxisPairTool does the same task.
  4. Disconnect the USB cable and push PS.The DS3 connects in about 10 seconds.

Many robots in one room

Each ESP32 connects to the first controller that is in pairing mode. In a class with many robots, pair one robot at a time. After the first pairing, the controller reconnects to the same ESP32.

  • Use BP32.enableNewBluetoothConnections(false) to stop new pairings after your controller connects.
  • Use BP32.forgetBluetoothKeys() to delete all stored pairings, for example when you give the robot to a different student. The robot sketch below does this when you hold BOOT for 2 seconds.
  • Label each controller and each robot with the same number.

Install Bluepad32

Option A · Arduino IDE board package (recommended)

  1. Open File → Preferences.Find Additional boards manager URLs.
  2. Add the two URLs below, one on each line.The first is the normal ESP32 package. The second is the Bluepad32 package.
  3. Open Tools → Board → Boards Manager.Install esp32 by Espressif if it is not installed. Install esp32_bluepad32 by Ricardo Quesada.
  4. Select a board in the “ESP32 + Bluepad32 Arduino” group.For a classic DevKit, select “ESP32 Dev Module” in that group.
  5. Open File → Examples → Bluepad32_ESP32 → Controller.Upload it. Open the Serial Monitor. Pair a controller.

Additional boards manager URLs


              https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
              https://raw.githubusercontent.com/ricardoquesada/esp32-arduino-lib-builder/master/bluepad32_files/package_esp32_bluepad32_index.json
            

What the board package changes

esp32_bluepad32 is a separate board package with its own copy of the ESP32 core. It does not replace the normal esp32 package. Both packages stay installed. The board that you select sets the package that compiles your sketch.

  • The newest package (4.1.0) contains Bluepad32 4.1.0 and Arduino-ESP32 core 2.0.17. The normal esp32 package is at core 3.x.
  • Core 2.x uses the old PWM functions ledcSetup() and ledcAttachPin(). Core 3.x uses ledcAttach(). The robot sketch below compiles on both.
  • Some libraries need core 3.x, for example ESP32Servo 3.x. With the Bluepad32 package, install ESP32Servo 1.2.1 or use LEDC directly. Read ESP32 libraries.
  • Do not install the Bluepad32 library from the Library Manager for an ESP32. That library is for Arduino boards with a NINA-W10 module (Nano RP2040 Connect, Nano 33 IoT, MKR WiFi 1010).
  • For other sketches, select a board in the normal esp32 group again.

Option B · ESP-IDF template with Arduino (PlatformIO or idf.py)

The esp-idf-arduino-bluepad32-template project uses a new ESP-IDF (5.x) with the Arduino core 3.x as a component. Use it for ESP32-C6 and ESP32-H2, for the newest controllers, or when you need core 3.x libraries. Open the folder in VS Code with PlatformIO, or build with idf.py build flash monitor. Your code goes in main/sketch.cpp. The Arduino IDE cannot open this project. In the template, use Console.printf() instead of Serial, or turn off the Bluepad32 console in sdkconfig.defaults. For PlatformIO setup, read IDE setup.

The Arduino API

Most used functions

FunctionGives / does
BP32.setup(&onConn, &onDisc)Starts Bluepad32 with your two callbacks. Call it once in setup().
BP32.update()Gets new controller data. Call it in each loop(). Returns true if new data came.
ctl->isConnected(), ctl->hasData()The controller is connected / sent new data since the last update().
ctl->isGamepad(), isMouse(), isKeyboard()The device type.
axisX(), axisY()Left stick, −511 … 512. Up and left are negative.
axisRX(), axisRY()Right stick, −511 … 512.
brake(), throttle()Analog L2 and R2, 0 … 1023.
a(), b(), x(), y()Face buttons, true while pushed.
l1(), r1(), l2(), r2(), thumbL(), thumbR()Shoulder buttons, digital triggers, stick clicks.
buttons(), dpad(), miscButtons()All buttons as a bitmask (table on the right).
miscSystem(), miscSelect(), miscStart()PS / Xbox button, Share / Select / −, Options / Start / +.
battery()0 = unknown, 1 = empty, 255 = full.
setColorLED(r, g, b)Light bar color (DualShock 4, DualSense).
setPlayerLEDs(bits)Player LEDs 1–4 (DS3, DualSense, Switch, Wii).
playDualRumble(delayMs, durationMs, weak, strong)Vibration. Magnitudes are 0–255.
ctl->disconnect()Disconnects this controller.
BP32.forgetBluetoothKeys()Deletes all stored pairings.
BP32.enableVirtualDevice(false)Stops the touchpad of a DS4 / DualSense from showing as a second “mouse” device. False is the default.
BP32.enableNewBluetoothConnections(b)Allows or stops new pairings.
BP32.localBdAddress()The Bluetooth address of the ESP32 (6 bytes).

Bitmasks

Bitbuttons()dpad()miscButtons()
0x0001A (✕)UpSystem (PS, Xbox, Home)
0x0002B (○)DownSelect (Share, Create, View, −)
0x0004X (□)RightStart (Options, Menu, +)
0x0008Y (△)LeftCapture (Mute, Share on Xbox)
0x0010L1 (shoulder L)
0x0020R1 (shoulder R)
0x0040L2 (trigger L)
0x0080R2 (trigger R)
0x0100Left stick click
0x0200Right stick click

The constants have names, for example BUTTON_A, BUTTON_SHOULDER_L, DPAD_UP and MISC_BUTTON_START. Example: if (ctl->dpad() & DPAD_UP). Two diagonal d-pad directions can be on at the same time.

Read the values

bp32_readout.ino


                #include <Bluepad32.h>

                ControllerPtr myControllers[BP32_MAX_GAMEPADS];

                void onConnectedController(ControllerPtr ctl) {
                  for (int i = 0; i < BP32_MAX_GAMEPADS; i++) {
                    if (myControllers[i] == nullptr) {
                      myControllers[i] = ctl;
                      Serial.printf("Controller connected, index=%d\n", i);
                      return;
                    }
                  }
                  Serial.println("Controller connected, but no free slot");
                }

                void onDisconnectedController(ControllerPtr ctl) {
                  for (int i = 0; i < BP32_MAX_GAMEPADS; i++) {
                    if (myControllers[i] == ctl) {
                      myControllers[i] = nullptr;
                      Serial.printf("Controller disconnected, index=%d\n", i);
                    }
                  }
                }

                void setup() {
                  Serial.begin(115200);
                  Serial.printf("Firmware: %s\n", BP32.firmwareVersion());
                  const uint8_t* addr = BP32.localBdAddress();
                  Serial.printf("BT address: %02X:%02X:%02X:%02X:%02X:%02X\n",
                                addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
                  BP32.setup(&onConnectedController, &onDisconnectedController);
                  BP32.enableVirtualDevice(false);   // no extra "mouse" for the touchpad
                }

                void loop() {
                  if (BP32.update()) {               // true when new data came
                    for (auto ctl : myControllers) {
                      if (ctl && ctl->isConnected() && ctl->hasData() && ctl->isGamepad()) {
                        Serial.printf("L %4d %4d  R %4d %4d  brake %4d  throttle %4d  "
                                      "buttons 0x%04x  dpad 0x%02x  misc 0x%02x\n",
                                      ctl->axisX(), ctl->axisY(), ctl->axisRX(), ctl->axisRY(),
                                      ctl->brake(), ctl->throttle(),
                                      ctl->buttons(), ctl->dpad(), ctl->miscButtons());
                      }
                    }
                  }
                  delay(10);   // let the Bluetooth task run (prevents a watchdog reset)
                }
              

Worked example: a two-motor robot with a servo arm

Two DC gearmotors drive the wheels through a TB6612FNG driver. A hobby servo moves an arm or a gripper. The left stick drives the robot (arcade) or each stick drives one side (tank). R2 and L2 move the servo. B stops the motors. For the motor driver, read DC motors. For the servo, read Servos. To select the motor gear ratio, read Gears primer.

Connections (classic ESP32 DevKit)

Part pinESP32Notes
TB6612 PWMA / AIN1 / AIN2GPIO 25 / 26 / 27Left motor (A01, A02)
TB6612 PWMB / BIN1 / BIN2GPIO 32 / 13 / 14Right motor (B01, B02)
TB6612 STBYGPIO 33HIGH = driver on
TB6612 VCC3V3Logic supply
TB6612 VMMotor battery +4.5–13.5 V, for example 2 × 18650 (7.4 V)
Servo signalGPIO 18Servo power from a 5–6 V supply, not from 3V3
All GNDGNDBattery, driver, servo supply and ESP32 together

With a DRV8833, connect two PWM pins to each motor (IN1/IN2) and write the PWM to one pin. The DC motors page shows that code. To power the ESP32 from the motor battery, use a buck converter. Read Power supplies.

Lift the wheels off the table for the first test. A wrong sign in the mixing code can make the robot drive away at full speed.

The mixing math

1 · Dead zone and scaling. A stick at rest seldom gives exactly 0. Values in the dead zone become 0. The remaining range is stretched again, so the speed starts at 0 at the dead-zone edge and gets to 1.0 at full stick.

2 · Invert Y. Stick up gives a negative axisY(), so use fwd = −axisY.

3a · Arcade: left = fwd + turn, right = fwd − turn. If one value is more than 1.0, divide both by the larger value. This keeps the turn ratio.

3b · Tank: left = −axisY, right = −axisRY. Tank mode is easy to understand and good for slow, exact turns.

4 · Max speed. Multiply by MAX_SPEED (0–1). Start with a low value for new drivers.

Use the simulator at the top of the page to test the dead zone and max speed. Then copy the values into the sketch.

The robot sketch

The sketch compiles with the Bluepad32 board package (core 2.0.17) and with core 3.x, because ESP_ARDUINO_VERSION_MAJOR selects the correct PWM functions.

bp32_robot.ino


            #include <Bluepad32.h>
            #include "esp_arduino_version.h"

            // TB6612FNG: motor A = left wheel, motor B = right wheel
            const int PWMA = 25, AIN1 = 26, AIN2 = 27;
            const int PWMB = 32, BIN1 = 13, BIN2 = 14;
            const int STBY = 33;
            const int SERVO_PIN = 18;
            const int BOOT_PIN  = 0;            // hold BOOT for 2 s to forget paired controllers

            const uint32_t MOTOR_FREQ = 20000;  // 20 kHz: no audible motor whine
            const uint8_t  MOTOR_BITS = 8;      // duty 0-255
            const uint32_t SERVO_FREQ = 50;     // 20 ms servo frame
            const uint8_t  SERVO_BITS = 14;     // duty 0-16383

            const int   DEAD_ZONE = 40;         // of 512: ignore small stick values
            const float MAX_SPEED = 0.8f;       // 0.0-1.0: limit the top speed
            const bool  TANK_MODE = false;      // false = arcade (left stick only)

            ControllerPtr driver = nullptr;     // only the first controller drives

            // ---------- PWM for core 2.x (Bluepad32 package) and core 3.x ----------
            void pwmBegin(int pin, int ch, uint32_t freq, uint8_t bits) {
            #if ESP_ARDUINO_VERSION_MAJOR >= 3
              ledcAttach(pin, freq, bits);
            #else
              ledcSetup(ch, freq, bits);
              ledcAttachPin(pin, ch);
            #endif
            }

            void pwmWrite(int pin, int ch, uint32_t duty) {
            #if ESP_ARDUINO_VERSION_MAJOR >= 3
              ledcWrite(pin, duty);
            #else
              ledcWrite(ch, duty);
            #endif
            }

            // ---------- Outputs ----------
            void setMotor(int in1, int in2, int pwmPin, int ch, float speed) {  // speed -1.0 ... 1.0
              speed = constrain(speed, -1.0f, 1.0f) * MAX_SPEED;
              digitalWrite(in1, speed > 0 ? HIGH : LOW);
              digitalWrite(in2, speed < 0 ? HIGH : LOW);   // both LOW = stop (coast)
              pwmWrite(pwmPin, ch, (uint32_t)(fabsf(speed) * 255.0f + 0.5f));
            }

            void stopMotors() {
              setMotor(AIN1, AIN2, PWMA, 0, 0);
              setMotor(BIN1, BIN2, PWMB, 1, 0);
            }

            void setServo(int angle) {
              angle = constrain(angle, 0, 180);
              uint32_t us = map(angle, 0, 180, 600, 2400);   // pulse width; examine your servo
              pwmWrite(SERVO_PIN, 2, us * 16383UL / 20000UL);
            }

            // ---------- Stick shaping ----------
            float shape(int32_t raw) {
              float v = constrain(raw, -512, 512) / 512.0f;
              float d = DEAD_ZONE / 512.0f;
              if (fabsf(v) < d) return 0.0f;
              return (v > 0 ? v - d : v + d) / (1.0f - d);   // 0 at the dead-zone edge, 1 at full stick
            }

            // ---------- Bluepad32 callbacks ----------
            void onConnectedController(ControllerPtr ctl) {
              if (driver == nullptr) {
                driver = ctl;
                ctl->setColorLED(0, 255, 0);               // light bar green (DS4, DualSense)
                ctl->playDualRumble(0, 200, 0x80, 0x40);   // short vibration: "connected"
                Serial.println("Driver connected");
              }
            }

            void onDisconnectedController(ControllerPtr ctl) {
              if (ctl == driver) {
                driver = nullptr;
                stopMotors();                                // failsafe: stop when the link is lost
                Serial.println("Driver disconnected: motors stopped");
              }
            }

            void setup() {
              Serial.begin(115200);
              pinMode(AIN1, OUTPUT); pinMode(AIN2, OUTPUT);
              pinMode(BIN1, OUTPUT); pinMode(BIN2, OUTPUT);
              pinMode(STBY, OUTPUT); digitalWrite(STBY, HIGH);
              pinMode(BOOT_PIN, INPUT_PULLUP);
              pwmBegin(PWMA, 0, MOTOR_FREQ, MOTOR_BITS);
              pwmBegin(PWMB, 1, MOTOR_FREQ, MOTOR_BITS);
              pwmBegin(SERVO_PIN, 2, SERVO_FREQ, SERVO_BITS);
              stopMotors();
              setServo(90);

              BP32.setup(&onConnectedController, &onDisconnectedController);
              BP32.enableVirtualDevice(false);
            }

            void loop() {
              BP32.update();

              if (driver && driver->isConnected()) {
                if (driver->b()) {                           // B = stop
                  stopMotors();
                } else {
                  float left, right;
                  if (TANK_MODE) {
                    left  = -shape(driver->axisY());         // stick up = negative value
                    right = -shape(driver->axisRY());
                  } else {
                    float fwd  = -shape(driver->axisY());
                    float turn =  shape(driver->axisX());
                    left  = fwd + turn;
                    right = fwd - turn;
                    float m = max(1.0f, max(fabsf(left), fabsf(right)));
                    left /= m;                               // keep the ratio, limit to 1.0
                    right /= m;
                  }
                  setMotor(AIN1, AIN2, PWMA, 0, left);
                  setMotor(BIN1, BIN2, PWMB, 1, right);
                }
                // R2 turns the servo one way, L2 the other way
                setServo(90 + (driver->throttle() - driver->brake()) * 90 / 1023);
              }

              // Hold BOOT for 2 s: forget all paired controllers
              static uint32_t bootDownMs = 0;
              if (digitalRead(BOOT_PIN) == LOW) {
                if (bootDownMs == 0) bootDownMs = millis();
                if (millis() - bootDownMs > 2000) {
                  BP32.forgetBluetoothKeys();
                  Serial.println("Pairings deleted. Pair a controller again.");
                  bootDownMs = 0;
                }
              } else {
                bootDownMs = 0;
              }

              delay(10);   // about 100 updates per second; lets the Bluetooth task run
            }
          

Do not push BOOT while you push EN (reset). That combination starts the download mode. If the robot turns when you push the stick forward, swap the two wires of one motor or change the sign of that motor in the code.

Troubleshooting

The controller does not connect

Make sure that the chip supports the controller (a PS4 or Switch controller needs a classic ESP32). Put the controller in pairing mode again. Disconnect the controller from the console, PC or phone that it used before, or turn that device off. Delete the old pairings with BP32.forgetBluetoothKeys().

The sketch does not compile

Make sure that the selected board is in the ESP32 + Bluepad32 Arduino group. Error messages about ledcAttach or ESP32Servo come from the core 2.x in the package. If the IDE shows “Multiple libraries were found”, remove the duplicate library.

The robot jerks or resets

Motor current pulls down the battery voltage, and the ESP32 resets (brownout). Use a separate supply or a good buck converter for the ESP32, and add a 470 µF capacitor at VM. Keep the delay() in loop() short, but do not remove it.

License. Bluepad32 is open source under the Apache 2.0 license (the Arduino part is Apache 2.0 or LGPL-2.1-or-later). It uses BTstack. BTstack is free for open-source and non-commercial projects. For a closed-source commercial ESP32 product, you must get a BTstack license from BlueKitchen.

Resources