CYBERDRIVE BLE
Kết nối ESP32 + MPU6050 qua BLE hoặc USB Serial để nghiêng tay cầm né chướng ngại vật và tăng tốc lên tới 280 km/h. Bạn cũng có thể lái thử ngay bằng phím mũi tên / W A S D.
Điều khiển 2 trục bằng độ nghiêng MPU6050: Trục Z (Đánh lái) & Trục X (Tăng/Giảm tốc)
Trình duyệt có thể chặn quyền Bluetooth bên trong khung Preview. Nếu nhấn Kết nối ESP32 (BLE) bị báo lỗi quyền, hãy bấm nút Tải file HTML rồi mở trực tiếp bằng Chrome hoặc Edge!
Kết nối ESP32 + MPU6050 qua BLE hoặc USB Serial để nghiêng tay cầm né chướng ngại vật và tăng tốc lên tới 280 km/h. Bạn cũng có thể lái thử ngay bằng phím mũi tên / W A S D.
Tự khôi phục bus I2C bị treo, tự dò 6 cặp chân SDA/SCL + địa chỉ 0x68/0x69, hỗ trợ mạch clone GY-521, gửi song song BLE Notify/Read + USB Serial 115200.
#include <Wire.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
// =========================================================================
// CYBERDRIVE BLE — ESP32 + MPU6050 (FIX TRIỆT ĐỂ I2C, CLONE GY-521 & BLE)
// Tương thích cả ESP32 Arduino Core 2.x và 3.x — Không cần cài thêm thư viện!
// =========================================================================
#define SERVICE_UUID "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
#define CHARACTERISTIC_UUID_RX "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
#define CHARACTERISTIC_UUID_TX "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
// Tự động dò 6 cặp chân I2C phổ biến (ESP32 WROOM: 21/22, đảo dây 22/21, 18/19, 16/17, ESP32-S3/C3: 8/9, 4/5)
const int I2C_PIN_CANDIDATES[][2] = {
{21, 22},
{22, 21},
{18, 19},
{16, 17},
{8, 9},
{4, 5}
};
const int NUM_PIN_CANDIDATES = sizeof(I2C_PIN_CANDIDATES) / sizeof(I2C_PIN_CANDIDATES[0]);
BLEServer *pServer = NULL;
BLECharacteristic *pTxCharacteristic = NULL;
volatile bool deviceConnected = false;
bool oldDeviceConnected = false;
unsigned long disconnectTimeMs = 0;
bool mpuReady = false;
bool useRepeatedStart = false; // Mặc định STOP (true) an toàn nhất cho cả chip clone GY-521
uint8_t mpuAddr = 0x68;
uint8_t mpuWhoAmI = 0x00;
int activeSdaPin = 21;
int activeSclPin = 22;
float roll = 0.0f, pitch = 0.0f, yaw = 0.0f;
float gyroXBias = 0.0f, gyroYBias = 0.0f, gyroZBias = 0.0f;
float medAx[3] = {0}, medAy[3] = {0}, medAz[3] = {1, 1, 1};
float medGx[3] = {0}, medGy[3] = {0}, medGz[3] = {0};
int medIdx = 0;
bool medFilled = false;
bool anglesInitialized = false;
unsigned long lastMicros = 0;
unsigned long lastRetryMs = 0;
unsigned long lastStatusPushMs = 0;
int readErrorStreak = 0;
float median3f(float a, float b, float c) {
if ((a <= b && b <= c) || (c <= b && b <= a)) return b;
if ((b <= a && a <= c) || (c <= a && a <= b)) return a;
return c;
}
float clampAngle180(float a) {
while (a > 180.0f) a -= 360.0f;
while (a < -180.0f) a += 360.0f;
return (fabs(a) < 0.05f) ? 0.0f : a;
}
void sendOutputText(const char* text) {
// Luôn in ra USB Serial (115200) để dùng được cả chế độ USB Serial trên Web Game
Serial.print(text);
if (pTxCharacteristic != NULL) {
// Luôn cập nhật giá trị để cả BLE Notify lẫn Polling Read đều lấy được dữ liệu tức thì
pTxCharacteristic->setValue((uint8_t*)text, strlen(text));
if (deviceConnected) {
pTxCharacteristic->notify();
}
}
}
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
yaw = 0.0f;
lastMicros = micros();
lastStatusPushMs = 0;
Serial.println("[BLE] Da ket noi voi trinh duyet Web!");
}
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
disconnectTimeMs = millis();
Serial.println("[BLE] Mat ket noi! Se tu dong phat lai BLE trong loop()...");
}
};
class MyRxCallbacks: public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
auto rawVal = pCharacteristic->getValue();
String rxValue = String(rawVal.c_str());
if (rxValue.indexOf("ZERO") >= 0 || rxValue.indexOf("START") >= 0 || rxValue.indexOf("1") >= 0) {
yaw = 0.0f;
lastStatusPushMs = 0;
Serial.println("[BLE] Nhan lenh tu Web -> Reset goc Z = 0!");
}
}
};
// Giải phóng bus I2C nếu MPU6050 giữ kẹt chân SDA ở mức LOW sau khi reset ESP32
void recoverI2CBus(int sda, int scl) {
pinMode(sda, INPUT_PULLUP);
pinMode(scl, OUTPUT);
for (int i = 0; i < 9; i++) {
digitalWrite(scl, LOW);
delayMicroseconds(10);
digitalWrite(scl, HIGH);
delayMicroseconds(10);
}
pinMode(sda, OUTPUT);
digitalWrite(sda, LOW);
delayMicroseconds(10);
digitalWrite(scl, HIGH);
delayMicroseconds(10);
digitalWrite(sda, HIGH);
delayMicroseconds(10);
}
bool i2cWriteReg(uint8_t addr, uint8_t reg, uint8_t val) {
Wire.beginTransmission(addr);
Wire.write(reg);
Wire.write(val);
return Wire.endTransmission(true) == 0;
}
bool i2cReadBytes(uint8_t addr, uint8_t startReg, uint8_t *buf, uint8_t len) {
Wire.beginTransmission(addr);
Wire.write(startReg);
if (Wire.endTransmission(!useRepeatedStart) != 0) {
useRepeatedStart = !useRepeatedStart;
Wire.beginTransmission(addr);
Wire.write(startReg);
if (Wire.endTransmission(!useRepeatedStart) != 0) return false;
}
uint8_t received = Wire.requestFrom((int)addr, (int)len, (int)true);
if (received != len) return false;
for (uint8_t i = 0; i < len; i++) {
buf[i] = Wire.read();
}
return true;
}
bool initMPU6050At(uint8_t addr) {
// 1. Ping nhanh địa chỉ I2C
Wire.beginTransmission(addr);
if (Wire.endTransmission(true) != 0) return false;
// 2. Đánh thức trực tiếp khỏi chế độ ngủ (không Soft Reset mạnh để tránh kẹt chip clone GY-521)
if (!i2cWriteReg(addr, 0x6B, 0x00)) return false;
delay(50);
// 3. Cấu hình DLPF ~44Hz, Gyro ±250dps, Accel ±2g
i2cWriteReg(addr, 0x19, 0x04);
i2cWriteReg(addr, 0x1A, 0x03);
i2cWriteReg(addr, 0x1B, 0x00);
i2cWriteReg(addr, 0x1C, 0x00);
delay(20);
// 4. Đọc WHO_AM_I (không từ chối chip clone nếu giá trị khác 0x68, miễn đọc được 14 byte đo!)
uint8_t id = 0;
if (i2cReadBytes(addr, 0x75, &id, 1)) {
mpuWhoAmI = id;
} else {
mpuWhoAmI = 0x00;
}
// 5. Đọc thử 14 byte đo thực tế từ thanh ghi 0x3B (Accel + Temp + Gyro)
uint8_t testBuf[14];
if (!i2cReadBytes(addr, 0x3B, testBuf, 14)) return false;
bool allZero = true, allFF = true;
for (int i = 0; i < 14; i++) {
if (testBuf[i] != 0x00) allZero = false;
if (testBuf[i] != 0xFF) allFF = false;
}
return !(allZero || allFF);
}
void calibrateGyroAll() {
long sumX = 0, sumY = 0, sumZ = 0;
int validSamples = 0;
uint8_t buf[6];
for (int i = 0; i < 100; i++) {
if (i2cReadBytes(mpuAddr, 0x43, buf, 6)) {
int16_t gx = (int16_t)((buf[0] << 8) | buf[1]);
int16_t gy = (int16_t)((buf[2] << 8) | buf[3]);
int16_t gz = (int16_t)((buf[4] << 8) | buf[5]);
if (abs(gx) < 3000 && abs(gy) < 3000 && abs(gz) < 3000) {
sumX += gx;
sumY += gy;
sumZ += gz;
validSamples++;
}
}
delay(3);
}
if (validSamples > 20) {
gyroXBias = (float)sumX / validSamples;
gyroYBias = (float)sumY / validSamples;
gyroZBias = (float)sumZ / validSamples;
} else {
gyroXBias = gyroYBias = gyroZBias = 0.0f;
}
}
bool tryDetectMPU() {
for (int p = 0; p < NUM_PIN_CANDIDATES; p++) {
int sda = I2C_PIN_CANDIDATES[p][0];
int scl = I2C_PIN_CANDIDATES[p][1];
Wire.end();
delay(10);
recoverI2CBus(sda, scl);
Wire.begin(sda, scl);
Wire.setClock(100000); // 100kHz chống nhiễu tối đa khi phát BLE
Wire.setTimeOut(50);
const uint8_t addrs[2] = {0x68, 0x69};
for (int a = 0; a < 2; a++) {
if (initMPU6050At(addrs[a])) {
activeSdaPin = sda;
activeSclPin = scl;
mpuAddr = addrs[a];
mpuReady = true;
readErrorStreak = 0;
Serial.printf("[MPU] KET NOI THANH CONG! SDA=%d, SCL=%d, ADDR=0x%02X, WHO_AM_I=0x%02X\n",
activeSdaPin, activeSclPin, mpuAddr, mpuWhoAmI);
calibrateGyroAll();
anglesInitialized = false;
lastMicros = micros();
return true;
}
}
}
mpuReady = false;
return false;
}
void setup() {
Serial.begin(115200);
delay(250);
Serial.println("\n=== CYBERDRIVE ESP32 + MPU6050 (AUTO-I2C + STABLE BLE) ===");
if (!tryDetectMPU()) {
Serial.println("[LOI] Chua tim thay MPU6050 tren 6 cap chan (21/22, 22/21, 18/19, 16/17, 8/9, 4/5)!");
Serial.println("[INFO] Kiem tra day VCC, GND, SDA, SCL. ESP32 se tu do lai moi 1 giay.");
}
BLEDevice::init("ESP32_CyberDrive_MPU");
BLEDevice::setMTU(128);
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
BLEService *pService = pServer->createService(SERVICE_UUID);
pTxCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID_TX,
BLECharacteristic::PROPERTY_NOTIFY | BLECharacteristic::PROPERTY_READ
);
pTxCharacteristic->addDescriptor(new BLE2902());
BLECharacteristic *pRxCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID_RX,
BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR
);
pRxCharacteristic->setCallbacks(new MyRxCallbacks());
pService->start();
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->setMinPreferred(0x06);
BLEDevice::startAdvertising();
lastMicros = micros();
Serial.println("[BLE] San sang! Hay ket noi BLE hoac USB Serial tren Web Game.");
}
void loop() {
// Tự phát lại quảng bá BLE an toàn ngoài callback
if (!deviceConnected && oldDeviceConnected) {
if (millis() - disconnectTimeMs >= 300) {
BLEDevice::startAdvertising();
Serial.println("[BLE] Da phat lai quang ba BLE!");
oldDeviceConnected = false;
}
}
if (deviceConnected && !oldDeviceConnected) {
oldDeviceConnected = true;
}
// Nếu chưa thấy MPU6050 -> gửi cảnh báo lỗi lên Web & tự dò lại mỗi 1 giây
if (!mpuReady) {
if (millis() - lastRetryMs >= 1000) {
lastRetryMs = millis();
if (!tryDetectMPU()) {
sendOutputText("ERR:NO_MPU\n");
}
}
delay(20);
return;
}
// Gửi 1 gói xác nhận phần cứng MPU OK ngay khi kết nối
if (lastStatusPushMs == 0) {
char statusBuf[48];
snprintf(statusBuf, sizeof(statusBuf), "STATUS:MPU_OK,%d,%d,0x%02X,0x%02X\n",
activeSdaPin, activeSclPin, mpuAddr, mpuWhoAmI);
sendOutputText(statusBuf);
lastStatusPushMs = millis();
}
unsigned long nowMicros = micros();
float dt = (nowMicros - lastMicros) / 1000000.0f;
lastMicros = nowMicros;
if (dt <= 0.0f || dt > 0.25f) dt = 0.03f;
uint8_t buf[14];
if (i2cReadBytes(mpuAddr, 0x3B, buf, 14)) {
readErrorStreak = 0;
int16_t rawAx = (int16_t)((buf[0] << 8) | buf[1]);
int16_t rawAy = (int16_t)((buf[2] << 8) | buf[3]);
int16_t rawAz = (int16_t)((buf[4] << 8) | buf[5]);
int16_t rawGx = (int16_t)((buf[8] << 8) | buf[9]);
int16_t rawGy = (int16_t)((buf[10] << 8) | buf[11]);
int16_t rawGz = (int16_t)((buf[12] << 8) | buf[13]);
float axRaw = rawAx / 16384.0f;
float ayRaw = rawAy / 16384.0f;
float azRaw = rawAz / 16384.0f;
float gxRaw = (rawGx - gyroXBias) / 131.0f;
float gyRaw = (rawGy - gyroYBias) / 131.0f;
float gzRaw = (rawGz - gyroZBias) / 131.0f;
// Lọc trung vị 3 mẫu ngay trên ESP32 để chặn xung nhiễu I2C cho cả 3 trục X, Y, Z
medAx[medIdx] = axRaw; medAy[medIdx] = ayRaw; medAz[medIdx] = azRaw;
medGx[medIdx] = gxRaw; medGy[medIdx] = gyRaw; medGz[medIdx] = gzRaw;
medIdx = (medIdx + 1) % 3;
if (medIdx == 0) medFilled = true;
float ax = medFilled ? median3f(medAx[0], medAx[1], medAx[2]) : axRaw;
float ay = medFilled ? median3f(medAy[0], medAy[1], medAy[2]) : ayRaw;
float az = medFilled ? median3f(medAz[0], medAz[1], medAz[2]) : azRaw;
float gx = medFilled ? median3f(medGx[0], medGx[1], medGx[2]) : gxRaw;
float gy = medFilled ? median3f(medGy[0], medGy[1], medGy[2]) : gyRaw;
float gz = medFilled ? median3f(medGz[0], medGz[1], medGz[2]) : gzRaw;
// Khử trôi vi mô đồng bộ trên cả 3 trục Gyro (X, Y, Z)
if (fabs(gx) < 0.35f) gx = 0.0f;
if (fabs(gy) < 0.35f) gy = 0.0f;
if (fabs(gz) < 0.35f) gz = 0.0f;
// Chặn xung Gyro vượt ngưỡng vật lý ±245°/s gây nhảy góc
if (fabs(gx) > 245.0f) gx = 0.0f;
if (fabs(gy) > 245.0f) gy = 0.0f;
if (fabs(gz) > 245.0f) gz = 0.0f;
// Góc nghiêng liên tục theo trục X (Roll) và trục Y (Pitch)
float accelRoll = atan2(ay, sqrt(ax * ax + az * az)) * 57.2957795f;
float accelPitch = atan2(-ax, sqrt(ay * ay + az * az)) * 57.2957795f;
float accMag = sqrt(ax * ax + ay * ay + az * az);
bool accStable = (accMag > 0.75f && accMag < 1.35f);
if (!anglesInitialized) {
roll = accelRoll;
pitch = accelPitch;
yaw = 0.0f;
anglesInitialized = true;
} else {
// Dự đoán góc theo Gyro cho cả 3 trục X, Y, Z (mượt, không nhảy khi rung lắc)
float predRoll = roll + gx * dt;
float predPitch = pitch + gy * dt;
// Chỉ hiệu chỉnh trọng lực Accel khi cảm biến không bị rung chấn mạnh (0.75g..1.35g)
if (accStable) {
roll = 0.96f * predRoll + 0.04f * accelRoll;
pitch = 0.96f * predPitch + 0.04f * accelPitch;
} else {
roll = predRoll;
pitch = predPitch;
}
yaw += gz * dt;
roll = clampAngle180(roll);
pitch = clampAngle180(pitch);
yaw = clampAngle180(yaw);
}
// Gói tin <= 20 byte: X(Roll), Y(Pitch), Z(Yaw) chuẩn dấu +/-
char payload[24];
snprintf(payload, sizeof(payload), "%.1f,%.1f,%.1f\n", roll, pitch, yaw);
sendOutputText(payload);
} else {
readErrorStreak++;
if (readErrorStreak > 15) {
mpuReady = false;
sendOutputText("ERR:NO_MPU\n");
}
}
delay(30); // ~33Hz: Mượt mà & không bao giờ nghẽn bộ đệm BLE trên Windows/Android
}