Skip to content

Cust17 Smart Car Technical Documentation

1. Project Overview

This project is a Mecanum wheel smart car project based on the ESP32-S3. It is developed using PlatformIO (Arduino framework), supports multiple control methods including Bluetooth gamepad control, MQTT remote control, web remote control, and TTL serial communication, and features PID closed-loop speed control, attitude sensing, OTA firmware upgrades, and more.

Project positioning: A four-wheel omnidirectional mobile chassis, suitable for robot education, ROS low-level platforms, remote monitoring, and other scenarios.


2. Hardware Platform

Hardware difference note: The project supports both V3 and V5 generations of cars with different motor parameters (see Head.h). The default values in the development documentation are for the V3 car; if using the V5 car, you need to switch the comments and measure the actual wheel spacing and wheelbase.

Component Description
Main control chip ESP32-S3 (ESP32-S3-DevKitC-1)
Motor driver QGPMaker EmotionPI driver board (MCPWM control)
Motor 4-channel DC geared encoder motors (1:90 reduction ratio / 1:50 reduction ratio)
Encoder Hall encoder, 48 lines/revolution (after frequency multiplication 48×4 = 192 pulses per revolution)
Wheel system Mecanum wheels / standard rubber wheels (switchable)
IMU MPU6050 six-axis gyroscope + accelerometer
Magnetometer QMC5883L three-axis electronic compass
Display SSD1306 OLED 128×64 (I2C)
LED WS2812B single LED
Servo 4-channel servo interface
Power supply 24V lithium battery (with voltage divider ADC sampling)

2.1 Pin Definitions

Encoder pins (configurable, default):

Channel Phase A Phase B
Motor 1 42 41
Motor 2 39 40
Motor 3 4 18
Motor 4 48 38

Motor PWM pins:

Channel PWM A PWM B
Motor 1 3 10
Motor 2 11 12
Motor 3 14 13
Motor 4 47 21

Servo pins: 5, 6, 7, 15

Other pins: - LED: GPIO 46 - Battery ADC: GPIO 2 - Serial 1: RX=15, TX=16


3. Software Architecture

src/
├── main.cpp          # 主程序:初始化和主循环
├── main.h            # 主头文件:声明和全局变量
└── html/             # 网页遥控器前端
    ├── joy.html      # 网页遥控器界面
    ├── main.js       # MQTT 通信和摇杆逻辑
    └── style.css     # 样式表

lib/
├── Head/
│   ├── Head.h        # 硬件参数配置和数据结构
│   └── utils.h       # 工具函数:WiFi、OTA、电池、IMU初始化等
├── Config/
│   ├── ConfigSeting.h  # 配置管理类声明
│   └── ConfigSeting.cpp # NVS 配置读写实现
├── motor/
│   ├── EMotionPI.h   # 电机驱动库 (QGPMaker)
│   └── EMotionPI.cpp # 直流电机、编码器电机、舵机、底盘控制
├── encoder/
│   ├── Encoder.h     # 编码器封装类
│   └── Encoder.cpp   # RPM 计算实现
├── Pid/
│   └── pid.h         # PID 控制器实现 (全头文件)
├── protocal/
│   └── protocol.h    # 串口通信协议 (全头文件)
├── ControlStick/
│   ├── BLEControlStick.h/cpp  # BLE 蓝牙手柄
│   ├── StickCB.h/cpp          # 手柄回调处理
│   ├── BLEControlStick.h/cpp  # BLE 手柄接入
├── MqttServer/
│   ├── MqttServer.h/cpp  # MQTT 远程控制
├── OTA/
│   ├── OTAupdate.h/cpp   # 远程固件升级
├── display/
│   ├── Display.h/cpp     # OLED 显示
├── kinematics/
│   ├── kinematics.h/cpp  # 运动学解算
├── mpu6050/
│   ├── Imu.h/cpp         # MPU6050 封装
│   └── MPU6050_*.h/cpp   # MPU6050 库
└── QMC5883LCompass/
    └── QMC5883LCompass.h/cpp  # 磁力计库

4. Module Details

4.1 Main Control Flow (main.cpp)

Initialization order (setup):

  1. Serial initialization (Serial + Serial1)
  2. Read configuration from NVS (encoder pins, speed parameters)
  3. Initialize encoders (4 channels)
  4. Initialize the BLE Bluetooth gamepad
  5. Initialize the QMC5883L magnetometer + MPU6050 gyroscope
  6. Connect WiFi, initialize the WS2812 LED
  7. Initialize the PID controller
  8. Initialize the MQTT service
  9. Create the FreeRTOS task xCore_task (running on Core 0)

Main loop (loop):

  • Heartbeat 20ms: process MQTT messages
  • Stop detection: automatically stops if no command for over 200ms
  • TTL serial data send/receive: parse the control protocol

Core 0 task (xCore_task):

  • Update BLE gamepad status
  • Encoder pin auto-test (triggered by holding the START key)
  • Attitude data reporting (every 100ms): voltage, angle, four-wheel RPM → linear velocity / angular velocity → CRC packing → Serial1 send
  • Voltage compensation: automatically reduces maximum RPM when below the 24V standard voltage

4.2 Control Modes

4.2.1 Bluetooth Gamepad Control

Connects to a standard gamepad via BLE (service UUID: 1812, characteristic UUID: 2A4D).

Gamepad button mapping:

Button Function
Left joystick forward/backward / lateral movement (speed proportional to magnitude)
Right joystick (left/right) rotation (Mecanum mode) / servo (normal mode)
D-pad ↑↓ forward/backward
D-pad ←→ lateral movement (Mecanum) / rotation (normal)
L1/R1 decrease / increase maximum speed limit
L2/R2 decrease / increase minimum starting speed
SELECT switch car type: Mecanum mode (blue LED) / normal mode (red LED)
START enter encoder auto-test mode
A/B/X/Y reserved function keys
Right joystick (up/down) servo angle control

4.2.2 Serial Protocol Control (TTL)

Communicates with the host computer via Serial1 (baud rate 115200). See Section 5 for the protocol.

4.2.3 MQTT Remote Control

Connects to the remote MQTT server (121.40.244.99:1883) via the MqttServer module, subscribes to the evtopic/wfjy/{clientId} topic, and receives control commands in JSON format.

4.2.4 Web Remote Control

The front-end project is located in src/html/, providing: - Dual-joystick control (lock/free modes switchable) - D-pad + A/B/X/Y buttons - MQTT direct communication (WebSocket) - Configurable communication identifier (stored in Cookie)

4.3 Kinematics

4.3.1 Mecanum Wheel Inverse Kinematics

wheelDelta = z_rpm × (轮距 + 轴距) / 轮周长

轮1 (左前) = x_rpm + y_rpm + wheelDelta
轮2 (右后) = x_rpm - y_rpm - wheelDelta
轮3 (左后) = x_rpm - y_rpm + wheelDelta
轮4 (右前) = x_rpm + y_rpm - wheelDelta

4.3.2 PID Closed-Loop Control

Each motor has an independent PID controller:

Parameter Value
Kp 0.25
Ki 0.02
Kd 0.5
Output range -100 ~ 100

Features: - Integral clamping ±10 - Dead-zone compensation (when PWM < deadPwm, set directly to deadPwm) - Full-load detection: when output reaches ±100 for 10 consecutive times, automatically reduces the speed factor (each time -0.1, minimum 50%)

4.4 Attitude Sensing

Fusion algorithm: complementary filter

fusion = 0.7 × 编码器角速度 + 0.3 × IMU 角速度
  • Encoder angular velocity: calculated via the four-wheel differential formula
  • IMU angular velocity: angle difference / time output by MPU6050 DMP (100ms)
  • The final output is smoothed by a low-pass filter (last × 0.3 + current × 0.7)

4.5 Encoder Test

Hold the gamepad START key to enter auto-test mode: 1. All 4 motors rotate in the same direction at low speed 2. Detect the change direction of the encoder count value 3. If the count is negative (wiring reversed), automatically swap A/B phases and save the configuration 4. Takes effect after restart

4.6 Configuration Management (NVS)

Uses ESP32 NVS (Preferences) storage:

Configuration item Description
model 0=Mecanum, 1=normal
max_speed maximum speed percentage (0-100)
min_speed minimum starting speed percentage (0-100)
E1_a~E4_b encoder pin definitions
wifi_ssid/pwd WiFi credentials
mqtt_cid MQTT client ID

The default configuration is stored as a JSON string with the key wifi_ssid and the namespace mynamespace.


5. Communication Protocol

Note: All multi-byte fields (data length, data body, CRC) use little-endian order, with the low byte first.

5.1 Packet Format

帧头(2B) + 数据长度(2B) + 设备ID(1B) + 命令字(1B) + 数据体(NB) + CRC16(2B)
Offset Size Description
0 1 Frame header 1: 0xAA
1 1 Frame header 2: 0x55
2 2 Data length (device ID + command + data body), little-endian
4 1 Device ID
5 1 Command word
6 N Data body (little-endian)
6+N 2 CRC16 (Modbus), little-endian

5.2 Command Definitions

Command Value Direction Description
CMD_pwmDrive 0x0A host → car PWM speed control
CMD_rosDrive 0x0B host → car three-axis speed control (mm/s)
CMD_rotation 0x0C host → car rotation control
CMD_pose 0x30 car → host attitude data reporting

5.3 Control Command Data Body

CMD_pwmDrive (0x0A) - PWM percentage control:

Offset Type Description
0-1 int16 LE X-axis speed (-100~100)
2-3 int16 LE Y-axis speed (-100~100)
4-5 int16 LE Z-axis rotation speed (-100~100)

Internal conversion: targetRPM = speed × maxRpm × 0.01

CMD_rosDrive (0x0B) - physical speed control:

Offset Type Description
0-1 int16 LE X-axis linear velocity (mm/s)
2-3 int16 LE Y-axis linear velocity (mm/s)
4-5 int16 LE Z-axis angular velocity (deg/s)

Internal conversion: linear velocity → RPM, angular velocity → differential RPM

5.4 Attitude Reporting Data Body (CMD_pose 0x30)

The car automatically sends to the serial port every 100ms:

Offset Type Description
0-1 int16 LE battery voltage (×0.1V)
2-3 int16 LE Z-axis angle (0~359°)
4-5 int16 LE X-axis linear velocity (mm/s)
6-7 int16 LE Y-axis linear velocity (mm/s)
8-9 int16 LE Z-axis angular velocity (deg/s, fused value)

5.5 CRC16 Algorithm (Modbus)

多项式: 0xA001
初始值: 0xFFFF
计算范围: 帧头 + 长度 + 设备ID + 命令 + 数据体

6. Usage Guide

6.1 Setting Up the Development Environment

  1. Install the VS Code + PlatformIO extension
  2. Open the cust17/ directory
  3. PlatformIO will automatically install the dependency libraries
  4. Compile and upload: PlatformIO: Upload

6.2 Project Configuration

platformio.ini key configuration:

[env:esp32dev]
platform = espressif32
board = esp32-s3-devkitc-1
framework = arduino
monitor_speed = 115200

Dependency libraries:

Library Purpose
NimBLE-Arduino BLE Bluetooth
ArduinoJson JSON parsing
ESP32Servo servo control
ESP32Encoder encoder counting
PubSubClient MQTT client
ESPAsyncWebServer-esphome asynchronous web server
FastLED WS2812 LED

6.3 Hardware Parameter Calibration

The following parameters in Head.h must be adjusted according to actual car body measurements:

Parameter Description Default value Measurement method
maxRpm motor theoretical maximum speed (RPM) 110 (1:90 reduction) / 120 (1:50 reduction) check motor datasheet
gear gear ratio of the reducer 90 / 50 reducer marking
encoderTicksPerRevolution encoder lines per revolution 48 encoder datasheet
deadPwm minimum PWM for motor startup 40 / 30 measured: gradually increase PWM until the wheel just turns
wheelCircumference wheel circumference (mm) π × 80 / π × 127 measured: distance the car moves forward in one wheel rotation
wheelSpacing wheel spacing (mm) 220 center distance between left and right wheels
wheelBase wheelbase (mm) 200 center distance between front and rear wheels

⚠️ Be sure to measure the above parameters according to the actual car body, otherwise it will cause inaccurate speed control, rotational offset, and other problems.

6.4 First Use

  1. Compile and upload the firmware to the ESP32-S3
  2. After power-on, the OLED displays the "Qiguopai" startup screen
  3. Search for and connect the Bluetooth gamepad (service name BLE-ControlStick)
  4. Use the gamepad SELECT key to switch car type mode
  5. Use the joystick to control vehicle movement

6.5 Speed Parameter Tuning

  • Real-time gamepad adjustment: L1/R1 adjust maximum speed, L2/R2 adjust starting speed
  • Code modification: see Head.h for hardware physical parameters (see Section 6.3), and pid.h for PID parameters
  • PID adjustment: the Kp/Ki/Kd in the setupPID() function in pid.h

7. Precautions

  1. Voltage compensation: when the battery voltage is below 24V, it automatically reduces speed; for each 1V decrease, the maximum speed decreases by 10%
  2. Overload protection: when the PID output is continuously at full load, the speed factor is automatically reduced to prevent motor overheating
  3. Stop safety: automatically stops if there is no control command for 200ms
  4. Encoder wiring: on first use, it is recommended to hold the START key to run the encoder self-check
  5. Communication conflict: the interval between Bluetooth gamepad commands and TTL serial commands must be greater than 500ms

8. Version History

Version Date Description
1.0 - initial version

Document generation date: June 2026