cpp
#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <BLECharacteristic.h>
#include <math.h> // For PI and trigonometric functions
// --- 1. 小车物理参数定义 (根据你的实际测量值修改!) ---
// 万向轮半径 (米)
#define WHEEL_RADIUS_M 0.030 // 例如: 60mm直径的轮子,半径就是30mm = 0.030m
// 机器人中心到每个万向轮中心的距离 (臂长,米)
#define ROBOT_RADIUS_M 0.100 // 例如: 100mm = 0.100m
// 编码器每转脉冲数 (PPR),通常是电机轴的脉冲数
#define ENCODER_PPR 11 // 例如:N20电机自带编码器,每圈11个脉冲
// 电机减速比 (例如 1:30)
#define MOTOR_GEAR_RATIO 30.0
// 编码器完整一周的有效脉冲数 (电机轴脉冲数 * 减速比)
// 如果编码器在减速箱输出轴,则直接是其PPR。请根据你的编码器类型确定。
#define ENCODER_TICKS_PER_WHEEL_REV (ENCODER_PPR * MOTOR_GEAR_RATIO) // 假设编码器测的是电机轴转速
// --- 2. ESP32-S3 引脚定义 (根据你的接线修改!) ---
// 电机驱动板 STBY 引脚
const int MOTOR_STBY_PIN = 13;
// 马达1 (右后)
const int M1_PWM_PIN = 4;
const int M1_DIR1_PIN = 5;
const int M1_DIR2_PIN = 6;
const int M1_ENC_A_PIN = 14;
const int M1_ENC_B_PIN = 15;
const int M1_PWM_CHANNEL = 0; // ESP32有16个PWM通道
// 马达2 (左后)
const int M2_PWM_PIN = 7;
const int M2_DIR1_PIN = 8;
const int M2_DIR2_PIN = 9;
const int M2_ENC_A_PIN = 16;
const int M2_ENC_B_PIN = 17;
const int M2_PWM_CHANNEL = 1;
// 马达3 (前)
const int M3_PWM_PIN = 10;
const int M3_DIR1_PIN = 11;
const int M3_DIR2_PIN = 12;
const int M3_ENC_A_PIN = 18;
const int M3_ENC_B_PIN = 19;
const int M3_PWM_CHANNEL = 2;
// PWM 参数
const int PWM_FREQ = 20000; // 20 KHz
const int PWM_RESOLUTION = 8; // 8位分辨率 (0-255)
// --- 3. PID 参数 (需要仔细调优!) ---
// 这些值是经验值,需要根据实际小车进行大量的实验和调整
// P (比例): 响应速度,K越大,响应越快,但可能过冲或震荡
// I (积分): 消除稳态误差,K越大,消除越快,但可能积分饱和或更慢的震荡
// D (微分): 抑制震荡,K越大,抑制越强,但可能对噪声敏感
const float KP = 0.5; // 比例增益
const float KI = 0.05; // 积分增益
const float KD = 0.01; // 微分增益
// --- 4. 蓝牙BLE UUIDs ---
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
// --- 全局变量 ---
BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
float target_vx = 0.0; // 目标X轴线速度 (m/s)
float target_vy = 0.0; // 目标Y轴线速度 (m/s)
float target_wz = 0.0; // 目标Z轴角速度 (rad/s)
// --- 5. 类定义 ---
// 5.1. Motor类:控制单个直流电机
class Motor {
public:
int pwmPin;
int dir1Pin;
int dir2Pin;
int channel;
Motor(int p, int d1, int d2, int ch) : pwmPin(p), dir1Pin(d1), dir2Pin(d2), channel(ch) {
pinMode(dir1Pin, OUTPUT);
pinMode(dir2Pin, OUTPUT);
ledcSetup(channel, PWM_FREQ, PWM_RESOLUTION);
ledcAttachPin(pwmPin, channel);
}
// 设置电机速度,speed范围为 -255到255 (对应8位PWM分辨率)
void setSpeed(int speed) {
// 限制速度在有效范围内
speed = constrain(speed, -255, 255);
if (speed == 0) {
digitalWrite(dir1Pin, LOW);
digitalWrite(dir2Pin, LOW);
ledcWrite(channel, 0); // 停止
} else if (speed > 0) { // 正转
digitalWrite(dir1Pin, HIGH);
digitalWrite(dir2Pin, LOW);
ledcWrite(channel, speed);
} else { // 反转
digitalWrite(dir1Pin, LOW);
digitalWrite(dir2Pin, HIGH);
ledcWrite(channel, -speed); // 负值取绝对值
}
}
// 强制停止电机
void stop() {
digitalWrite(dir1Pin, LOW);
digitalWrite(dir2Pin, LOW);
ledcWrite(channel, 0);
}
};
// 5.2. MotorEncoder类:读取编码器脉冲和计算速度
// 注意:ISR (中断服务程序) 必须是全局函数,不能是类的成员函数。
// 所以我们将编码器实例定义为全局变量,并在ISR中访问它们。
class MotorEncoder {
public:
int pinA, pinB;
volatile long count; // 编码器脉冲计数
volatile long lastCount; // 用于速度计算的上一次计数
unsigned long lastSampleTime; // 用于速度计算的上一次采样时间
float currentRPM; // 当前转速 (RPM)
MotorEncoder(int pA, int pB) : pinA(pA), pinB(pB), count(0), lastCount(0), lastSampleTime(0), currentRPM(0.0f) {
pinMode(pinA, INPUT_PULLUP);
pinMode(pinB, INPUT_PULLUP);
}
// 在ISR中调用此函数更新计数
void IRAM_ATTR update() {
int valA = digitalRead(pinA);
int valB = digitalRead(pinB);
if (valA == HIGH) {
if (valB == LOW) count++; // 假设A超前B为正转
else count--;
} else {
if (valB == HIGH) count++;
else count--;
}
}
// 定期调用此函数计算RPM
void calculateSpeed() {
unsigned long currentTime = millis();
if (currentTime - lastSampleTime >= 100) { // 每100ms计算一次速度
long deltaCount = count - lastCount;
float deltaT_sec = (currentTime - lastSampleTime) / 1000.0f; // 时间间隔 (秒)
if (deltaT_sec > 0) {
// 将脉冲数转换为每秒转数,再转换为RPM
// (deltaCount / ENCODER_TICKS_PER_WHEEL_REV) 是轮子的转数
currentRPM = (deltaCount / (float)ENCODER_TICKS_PER_WHEEL_REV) * (60.0f / deltaT_sec);
} else {
currentRPM = 0.0f;
}
lastCount = count;
lastSampleTime = currentTime;
}
}
};
// 5.3. PIDController类:实现PID算法
class PIDController {
public:
float Kp, Ki, Kd;
float setpoint; // 目标值
float input; // 实际值
float output; // PID输出
float errorSum; // 误差积分
float lastError; // 上次误差
unsigned long lastTime; // 上次计算时间
PIDController(float p, float i, float d) :
Kp(p), Ki(i), Kd(d),
setpoint(0), input(0), output(0),
errorSum(0), lastError(0), lastTime(0) {}
// 计算PID输出
float compute(float actualValue) {
unsigned long now = millis();
float timeChange = (float)(now - lastTime) / 1000.0f; // 时间间隔 (秒)
if (timeChange == 0) return output; // 避免除以零
float error = setpoint - actualValue;
errorSum += (error * timeChange);
float dError = (error - lastError) / timeChange;
// PID公式
output = Kp * error + Ki * errorSum + Kd * dError;
lastError = error;
lastTime = now;
// 限制输出范围,例如0-255,如果电机需要反转,则可能是-255到255
// 这里假设输出将直接用于PWM,所以需要钳位
output = constrain(output, -255, 255);
return output;
}
void setSetpoint(float s) { setpoint = s; }
void resetIntegral() { errorSum = 0; } // 在目标值变化或停止时重置积分项,避免积分饱和
};
// --- 6. 实例化对象 ---
Motor motor1(M1_PWM_PIN, M1_DIR1_PIN, M1_DIR2_PIN, M1_PWM_CHANNEL);
Motor motor2(M2_PWM_PIN, M2_DIR1_PIN, M2_DIR2_PIN, M2_PWM_CHANNEL);
Motor motor3(M3_PWM_PIN, M3_DIR1_PIN, M3_DIR2_PIN, M3_PWM_CHANNEL);
MotorEncoder encoder1(M1_ENC_A_PIN, M1_ENC_B_PIN);
MotorEncoder encoder2(M2_ENC_A_PIN, M2_ENC_B_PIN);
MotorEncoder encoder3(M3_ENC_A_PIN, M3_ENC_B_PIN);
PIDController pid1(KP, KI, KD);
PIDController pid2(KP, KI, KD);
PIDController pid3(KP, KI, KD);
// --- 7. ISR 全局函数 (用于编码器中断) ---
void IRAM_ATTR isr1() { encoder1.update(); }
void IRAM_ATTR isr2() { encoder2.update(); }
void IRAM_ATTR isr3() { encoder3.update(); }
// --- 8. 万向轮运动学函数 (逆运动学) ---
// 将机器人目标线速度 (Vx, Vy) 和角速度 (Wz) 转换为每个轮子的目标角速度 (rad/s)
// 然后将角速度转换为RPM,再转换为PID目标值
void calculate_motor_rpms(float vx, float vy, float wz, float& rpm1, float& rpm2, float& rpm3) {
// 轮子相对于机器人X轴的安装角度 (弧度)
// 假设M1在机器人右后 (210度或-150度)
// M2在机器人左后 (150度或-210度)
// M3在机器人前 (90度或-270度)
// 这里我们使用经典的120度分布,M1 0度,M2 120度,M3 240度。
// 请根据你的轮子实际安装位置和坐标系定义来调整这些角度。
// 假设 M1 0 deg, M2 120 deg, M3 240 deg (相对于机器人前进方向)
const float theta1 = 0; // Motor 1 (Right-Front) - or adjust based on your setup
const float theta2 = 2 * PI / 3.0; // Motor 2 (Left-Front)
const float theta3 = 4 * PI / 3.0; // Motor 3 (Rear)
// 确保你的轮子方向和坐标系一致。
// 比如:如果M1是右后,M2是左后,M3是前,并且M3是0度,M1 120度,M2 240度
// 则 theta1 = PI/2, theta2 = PI/2 + 2*PI/3, theta3 = PI/2 + 4*PI/3
// 逆运动学公式,计算每个轮子的线速度 (m/s)
float v_wheel1 = (vx * cos(theta1) + vy * sin(theta1) + ROBOT_RADIUS_M * wz);
float v_wheel2 = (vx * cos(theta2) + vy * sin(theta2) + ROBOT_RADIUS_M * wz);
float v_wheel3 = (vx * cos(theta3) + vy * sin(theta3) + ROBOT_RADIUS_M * wz);
// 将线速度转换为轮子角速度 (rad/s)
float omega1 = v_wheel1 / WHEEL_RADIUS_M;
float omega2 = v_wheel2 / WHEEL_RADIUS_M;
float omega3 = v_wheel3 / WHEEL_RADIUS_M;
// 将角速度 (rad/s) 转换为 RPM (每分钟转数)
rpm1 = omega1 * 60.0 / (2 * PI);
rpm2 = omega2 * 60.0 / (2 * PI);
rpm3 = omega3 * 60.0 / (2 * PI);
}
// --- 9. BLE 回调函数 ---
class MyServerCallbacks : public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
Serial.println("BLE Client Connected!");
// 连接后停止小车,重置积分项
target_vx = 0; target_vy = 0; target_wz = 0;
pid1.resetIntegral(); pid2.resetIntegral(); pid3.resetIntegral();
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
Serial.println("BLE Client Disconnected!");
// 断开连接后停止小车
motor1.stop();
motor2.stop();
motor3.stop();
}
};
class MyCharacteristicCallbacks : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
std::string rxValue = pCharacteristic->getValue();
if (rxValue.length() > 0) {
Serial.print("Received Command: ");
for (int i = 0; i < rxValue.length(); i++) {
Serial.print(rxValue[i]);
}
Serial.println();
// 解析接收到的命令
// 命令格式可以是简单的单字符指令,或者更复杂的字符串
// 这里我们使用单字符指令,方便手机APP发送:
// 'F': 前进 (Forward)
// 'B': 后退 (Backward)
// 'L': 左移 (Strafe Left)
// 'R': 右移 (Strafe Right)
// 'C': 顺时针旋转 (Rotate Clockwise)
// 'A': 逆时针旋转 (Rotate Anti-clockwise)
// 'S': 停止 (Stop)
// 示例速度值 (可根据需求调整)
float linear_speed = 0.2; // 0.2 m/s
float angular_speed = PI / 4.0; // 0.785 rad/s (45度/秒)
// 重置目标速度
target_vx = 0.0;
target_vy = 0.0;
target_wz = 0.0;
if (rxValue.length() == 1) {
char cmd = rxValue[0];
switch (cmd) {
case 'F': target_vx = linear_speed; break; // 前进
case 'B': target_vx = -linear_speed; break; // 后退
case 'L': target_vy = linear_speed; break; // 左移
case 'R': target_vy = -linear_speed; break; // 右移
case 'C': target_wz = -angular_speed; break; // 顺时针旋转
case 'A': target_wz = angular_speed; break; // 逆时针旋转
case 'S': /* already 0 */ break; // 停止
default: Serial.println("Unknown command!"); break;
}
} else {
// 如果接收到的是类似 "Vx,Vy,Wz" 的字符串,则进行解析
// 这部分需要更复杂的字符串解析,此处省略以保持简洁。
// 建议使用简单的指令或JSON格式。
Serial.println("Complex command parsing not implemented in this example.");
}
}
}
};
// --- 10. setup() 函数 ---
void setup() {
Serial.begin(115200);
Serial.println("ESP32-S3 Omni-Wheel Robot Booting...");
// 初始化电机STBY引脚
pinMode(MOTOR_STBY_PIN, OUTPUT);
digitalWrite(MOTOR_STBY_PIN, HIGH); // 开启电机驱动
// 附着编码器中断
attachInterrupt(digitalPinToInterrupt(M1_ENC_A_PIN), isr1, CHANGE); // CHANGE模式在任何电平变化时触发
attachInterrupt(digitalPinToInterrupt(M2_ENC_A_PIN), isr2, CHANGE);
attachInterrupt(digitalPinToInterrupt(M3_ENC_A_PIN), isr3, CHANGE);
// 初始化BLE
BLEDevice::init("ESP32-S3_OmniBot"); // 设置蓝牙设备名称
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
BLEService *pService = pServer->createService(SERVICE_UUID);
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE
);
pCharacteristic->setCallbacks(new MyCharacteristicCallbacks());
pService->start();
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID); // 广播服务UUID
pAdvertising->setScanResponse(true); // 允许扫描响应
pAdvertising->setMinPreferred(0x06); // set these two to increase connectability
pAdvertising->setMinPreferred(0x12);
BLEDevice::startAdvertising();
Serial.println("BLE advertising started. Waiting for connection...");
// 初始状态,所有电机停止
motor1.stop();
motor2.stop();
motor3.stop();
Serial.println("Setup Complete!");
}
// --- 11. loop() 函数 ---
void loop() {
// BLE连接状态管理
if (!deviceConnected) {
// 如果断开连接,尝试重新开始广播
if (pServer->getAdvertising()->is </*Advertising */> (false)) {
BLEDevice::startAdvertising();
Serial.println("Restarting BLE advertising...");
}
delay(500); // 节省功耗
return;
}
// --- 1. 更新编码器速度 ---
encoder1.calculateSpeed();
encoder2.calculateSpeed();
encoder3.calculateSpeed();
// --- 2. 根据目标机器人速度计算每个电机的目标RPM ---
float target_rpm1, target_rpm2, target_rpm3;
calculate_motor_rpms(target_vx, target_vy, target_wz, target_rpm1, target_rpm2, target_rpm3);
// --- 3. 设置PID目标值并计算输出 ---
pid1.setSetpoint(target_rpm1);
pid2.setSetpoint(target_rpm2);
pid3.setSetpoint(target_rpm3);
int motor_pwm1 = round(pid1.compute(encoder1.currentRPM));
int motor_pwm2 = round(pid2.compute(encoder2.currentRPM));
int motor_pwm3 = round(pid3.compute(encoder3.currentRPM));
// --- 4. 驱动电机 ---
motor1.setSpeed(motor_pwm1);
motor2.setSpeed(motor_pwm2);
motor3.setSpeed(motor_pwm3);
// --- 5. 调试信息输出 (可选) ---
static unsigned long lastPrintTime = 0;
if (millis() - lastPrintTime > 200) { // 每200ms打印一次
Serial.printf("Target Vx:%.2f, Vy:%.2f, Wz:%.2f | ", target_vx, target_vy, target_wz);
Serial.printf("M1_RPM:%.2f/%.2f(PWM:%d) | ", encoder1.currentRPM, target_rpm1, motor_pwm1);
Serial.printf("M2_RPM:%.2f/%.2f(PWM:%d) | ", encoder2.currentRPM, target_rpm2, motor_pwm2);
Serial.printf("M3_RPM:%.2f/%.2f(PWM:%d)\n", encoder3.currentRPM, target_rpm3, motor_pwm3);
lastPrintTime = millis();
}
// 短暂延迟以避免CPU过度占用 (根据实际需要调整)
delay(10);
}