What you will build
A handheld controller and a browser flight game. Tilt forward to dive, back to climb, sideways to bank. Four buttons control throttle up, throttle down, camera view and reset. Fly through checkpoint rings and try a landing. Anyone without hardware can play in Demo Mode with the keyboard.
How it works
This project introduces the XBOT Motion Controller firmware, reused by Projects 12 and 13. The ESP32 reads the MPU6050, fuses accelerometer and gyroscope with a complementary filter into smooth pitch and roll, and sends one line of JSON 50 times a second over the USB cable:
{"p":-12.4,"r":5.1,"gz":0.02,"b":3,"t":104233}
| Field | Meaning | Unit |
|---|---|---|
p |
Pitch (nose up positive) | degrees |
r |
Roll (right wing down positive) | degrees |
gz |
Yaw rate | rad/s |
b |
Buttons bitmask (bit0 = GPIO 25 … bit3 = GPIO 33) | — |
t |
Controller uptime | ms |
The browser connects with Web Serial (desktop Chrome or Edge, HTTPS), parses each line, and maps pitch/roll to the aircraft. If no valid line arrives for 500 ms, controls return to neutral and the HUD shows Controller lost.
Parts
| Part | Qty | Purpose | Required |
|---|---|---|---|
| ESP32-DevKitC V4 + USB data cable | 1 | Controller | Yes |
| MPU6050 breakout (GY-521) | 1 | Motion | Yes |
| Tactile buttons | 4 | Throttle +/–, camera, reset | Yes |
| Half-size breadboard | 1 | Handheld base | Yes |
| Laptop with Chrome or Edge | 1 | Runs the simulator | Yes |
| 0.96" OLED, 3D-printed or card grip | 1 | Telemetry, comfort | Optional |
Build steps
- MPU6050: VCC → 3V3, GND → GND, SDA → GPIO 21, SCL → GPIO 22. Mount it flat, chip facing up, arrow pointing "forward".
- Buttons to GND from GPIO 25 (throttle +), 27 (throttle –), 32 (camera), 33 (reset).
- Install Adafruit MPU6050. Upload the XBOT Motion Controller firmware.
- Open the Serial Monitor at 115200 baud. Checkpoint: JSON lines scroll; tilting changes
pandr; buttons changeb. Close the Serial Monitor (only one program can use the port). - Open
/projects/flight-simulator/playin Chrome or Edge. Click Connect Controller and choose the ESP32's port. - Hold the controller level and click Calibrate.
- Fly: take off with throttle +, pass the first three rings, then land on the runway.
- Unplug the cable mid-flight: the plane levels out and the HUD warns you.
Try it in the browser
This is the main experience. Demo Mode (keyboard: W/S pitch, A/D roll, Shift/Ctrl throttle, C camera, R reset) and Live Controller mode sit side by side. Telemetry panel shows pitch, roll, throttle and data rate, labelled Demo or Live accordingly.
Code
XBOT Motion Controller firmware (shared by Projects 11–13).
Download xbot-motion-controller.ino
// XBOT Motion Controller — XBOTNOW
// Board: ESP32-DevKitC V4 · Core: esp32 v3.x · Library: Adafruit MPU6050
// Output: JSON lines @ 115200 baud, 50 Hz
#include <Adafruit_MPU6050.h>
const int BTN[4] = {25, 27, 32, 33};
const float ALPHA = 0.96; // complementary filter: trust gyro short-term
Adafruit_MPU6050 mpu;
float pitch = 0, roll = 0, gxBias = 0, gyBias = 0, gzBias = 0;
unsigned long last = 0;
void setup() {
Serial.begin(115200);
for (int i = 0; i < 4; i++) pinMode(BTN[i], INPUT_PULLUP);
if (!mpu.begin()) { Serial.println("{\"err\":\"mpu\"}"); while (1) delay(500); }
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
sensors_event_t a, g, t;
for (int i = 0; i < 200; i++) { // keep still: gyro bias
mpu.getEvent(&a, &g, &t);
gxBias += g.gyro.x; gyBias += g.gyro.y; gzBias += g.gyro.z; delay(5);
}
gxBias /= 200; gyBias /= 200; gzBias /= 200;
last = micros();
}
void loop() {
sensors_event_t a, g, t; mpu.getEvent(&a, &g, &t);
float dt = (micros() - last) / 1e6; last = micros();
float accPitch = atan2(-a.acceleration.x, sqrt(sq(a.acceleration.y) + sq(a.acceleration.z))) * 57.2958;
float accRoll = atan2(a.acceleration.y, a.acceleration.z) * 57.2958;
pitch = ALPHA * (pitch + (g.gyro.y - gyBias) * 57.2958 * dt) + (1 - ALPHA) * accPitch;
roll = ALPHA * (roll + (g.gyro.x - gxBias) * 57.2958 * dt) + (1 - ALPHA) * accRoll;
int b = 0;
for (int i = 0; i < 4; i++) if (digitalRead(BTN[i]) == LOW) b |= (1 << i);
Serial.printf("{\"p\":%.1f,\"r\":%.1f,\"gz\":%.2f,\"b\":%d,\"t\":%lu}\n",
pitch, roll, g.gyro.z - gzBias, b, millis());
delay(20); // ~50 Hz
}
Browser: Web Serial connection (shared module xbot-serial.js).
// xbot-serial.js — XBOTNOW. Requires desktop Chrome/Edge over HTTPS.
export const controller = { live: false, p: 0, r: 0, gz: 0, b: 0, lastSeen: 0 };
export function webSerialSupported() { return 'serial' in navigator; }
export async function connect() {
const port = await navigator.serial.requestPort(); // user picks the ESP32
await port.open({ baudRate: 115200 });
const reader = port.readable.pipeThrough(new TextDecoderStream()).getReader();
let buf = '';
controller.live = true;
(async () => {
try {
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buf += value;
let i;
while ((i = buf.indexOf('\n')) >= 0) {
const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1);
try {
const d = JSON.parse(line);
if (typeof d.p === 'number' && typeof d.r === 'number') {
Object.assign(controller, d, { lastSeen: performance.now() });
}
} catch { /* ignore partial or invalid lines */ }
}
}
} finally { controller.live = false; }
})();
}
// Call every frame. Returns neutral input when data is stale (> 500 ms).
export function readInput(calib = { p: 0, r: 0 }) {
const fresh = controller.live && performance.now() - controller.lastSeen < 500;
if (!fresh) return { pitch: 0, roll: 0, gz: 0, buttons: 0, fresh: false };
return { pitch: controller.p - calib.p, roll: controller.r - calib.r, gz: controller.gz, buttons: controller.b, fresh: true };
}
Flight mapping (inside the Three.js render loop).
const inp = demoMode ? keyboardInput() : readInput(calibration);
const clamp = (v, m) => Math.max(-m, Math.min(m, v));
plane.pitchRate = clamp(inp.pitch, 40) / 40 * 1.2; // rad/s at full tilt
plane.rollRate = clamp(inp.roll, 45) / 45 * 2.0;
if (inp.buttons & 1) plane.throttle = Math.min(1, plane.throttle + 0.01);
if (inp.buttons & 2) plane.throttle = Math.max(0, plane.throttle - 0.01);
hud.status = demoMode ? 'Demo' : inp.fresh ? 'Live controller' : 'Controller lost';
Scene requirements for the web team: ground plane with runway, 8 checkpoint rings, chase and cockpit cameras, simple arcade lift/drag (no stall in Easy mode), a reduced-motion option, and an unsupported-browser message that offers Demo Mode.
Troubleshooting
| Symptom | Likely cause | Check |
|---|---|---|
| No "Connect Controller" button | Browser lacks Web Serial | Use desktop Chrome or Edge; Safari, Firefox and phones use Demo Mode |
| Port list empty | Charge-only cable or driver | Data cable; CP210x/CH340 driver |
| "Failed to open serial port" | Serial Monitor still open | Close Arduino Serial Monitor |
| Plane drifts with controller level | Not calibrated | Hold level, click Calibrate |
| Controls reversed | Sensor mounted differently | Use the Invert Pitch/Roll toggles in Settings |
Safety and limitations
Arcade simulator only. Never connect this controller or code to a real aircraft, drone or vehicle. Include a reduced-motion setting for players prone to motion sickness.
Checklist
Next project
3D Gesture Sculptor: same controller, creative output.

