【花雕学编程】Arduino BLDC 之机器人 A*算法路径绘图与电机控制

Arduino BLDC 之机器人 A 路径绘图与电机控制,本质上是用栅格地图把环境离散化,再用 A 启发式搜索生成从起点到目标点的最优航点序列,最后通过 BLDC 差速闭环把折线航点转换成可执行的线速度和角速度指令。** 它的难点不在于单独跑通 A* 或单独驱动电机,而在于让“地图分辨率、搜索代价、路径平滑、定位精度、BLDC 速度闭环”形成一条稳定闭环。
主要特点
. 栅格地图是路径绘图的基础
环境通常被离散化为二维数组,每个栅格标记为自由、障碍或未知。 地图可预先录入,也可通过超声波、ToF、激光雷达或视觉传感器增量更新。对 Arduino 这类资源受限平台,地图尺寸通常要控制在 20×20 到 30×30 栅格左右;更复杂场景建议迁移到 ESP32、Teensy 或上位机。
. A 搜索兼顾最优性与效率
A 通过 f(n) = g(n) + h(n) 进行搜索:g(n) 为起点到当前节点的实际代价,h(n) 为到目标的启发式估计。 在嵌入式实现中,常用曼哈顿距离或整数欧氏距离作为启发函数,避免浮点运算;开放列表可用固定数组或二叉堆管理,并限制最大搜索节点数,防止内存溢出。 若希望减少频繁转向,可在扩展代价中加入转向惩罚,使路径更贴近差速底盘的运动特性。
. 路径必须平滑后才能交给电机执行
原始 A* 输出通常是折线或锯齿状栅格序列,直接跟踪会造成频繁启停、急转和轮胎打滑。 常见后处理包括:视线剪枝删除冗余航点、圆弧插补适配差速转向、贝塞尔曲线或样条曲线提升曲率连续性。 平滑后的路径再按固定间距采样,生成带航向角的目标点序列。
. 电机控制采用“差速解算 + BLDC 速度闭环”
A* 输出的是几何路径,BLDC 需要的是速度指令。通常先根据当前位姿与下一航点计算期望线速度和角速度,再通过差速模型分解为左右轮目标速度:
左轮速度 ≈ V − ω × L / 2
右轮速度 ≈ V + ω × L / 2
其中 L 为轮距。左右 BLDC 在编码器反馈下运行速度闭环,SimpleFOC 等平台可直接使用 MotionControlType::velocity 模式。 若使用 FOC 电流环,还可进一步把速度指令映射为扭矩指令,提高低速跟踪和平滑性。
. 分层架构更适合嵌入式落地
推荐分为三层:
感知与建图层:传感器数据 → 栅格地图更新。
规划层:A* 搜索 → 路径平滑 → 航点序列。
执行层:定位估计 → 差速解算 → BLDC 速度/扭矩闭环。
Arduino Uno/Nano 适合做轻量执行节点;若同时运行 A*、建图和 FOC,更推荐 ESP32、Teensy 4.1 或 STM32。
应用场景
教学与竞赛平台:在已知栅格地图或迷宫中实现从起点到终点的最短路径规划与跟踪,训练算法、传感器和电机控制能力。
微型 AGV / AMR 原型:在小型货架区或实验场地内按预设地图取货、搬运,验证全局规划与差速跟踪。
室内巡检机器人:在走廊、实验室、仓库等静态环境中执行定点巡查,A* 提供全局路径,BLDC 提供平稳移动。
动态迷宫 / 重规划验证:地图发生变化时重新运行 A*,或在局部窗口内进行重规划,验证动态环境下的导航能力。
SLAM 导航原型:上位机或 ESP32 负责 SLAM 建图,A* 作为全局规划器,下位机负责 BLDC 差速执行。
需要注意的事项
地图分辨率要与机器人尺寸匹配
栅格过小会显著增加搜索和内存开销;栅格过大则可能把可行通道误判为障碍。一般栅格边长应小于机器人最小通过宽度的一半,并对障碍物做适当膨胀,留出安全余量。
A 实现要避免动态内存和浮点浪费*
在 AVR 平台上,节点结构应尽量紧凑,开放列表优先使用固定数组或预分配队列;启发函数尽量用整数距离;搜索节点数要设上限,超限后应返回失败或降级重规划。
路径平滑不能省略
未经平滑的 A* 路径会让差速底盘频繁急转,导致轮胎磨损、定位漂移和电流尖峰。至少应做航点剪枝和转弯减速;条件允许时加入圆弧或贝塞尔平滑。
定位误差会直接破坏路径跟踪
仅靠编码器里程计容易因打滑累积误差。可加入 IMU 航向校正、地标校正、视觉/UWB 定位或外部定位模块。到达每个航点时应设置容差区,避免机器人为了“精确对齐”而原地振荡。
BLDC 闭环要先于复杂规划调稳
如果左右轮速度环未调通、编码器方向未校准、轮径和轮距未标定,路径跟踪必然跑偏。应先验证单电机 FOC/速度闭环,再验证差速直线和定点转向,最后再接入 A* 路径跟踪。
动态障碍需要局部策略配合
A* 适合静态全局规划,遇到突然出现的人员、车辆或移动障碍时,不宜每次都全图重算。可叠加 DWA、人工势场或局部窗口重规划,使机器人先安全避让,再重新接回全局路径。
电源与 EMC 不能忽视
BLDC 加减速和转向时电流变化大,可能引起 MCU 复位、编码器跳变或传感器误报。应做好动力电源与控制电源隔离、母线电容补偿、信号线屏蔽和急停保护。

1、全局 A* + DWA 局部速度采样(农田/巡检场景)
全局 A* 给出栅格路径,DWA(动态窗口法)在路径点跟踪时实时采样速度,兼顾避障与运动学约束。
#include <SimpleFOC.h>
#include <vector>
#include <cmath>
// ===== 电机对象 =====
BLDCMotor motorL(7);
BLDCMotor motorR(7);
BLDCDriver3PWM driverL(9, 5, 6, 8);
BLDCDriver3PWM driverR(3, 10, 11, 7);
Encoder encL(2, 4, 2048);
Encoder encR(3, 5, 2048);
// ===== 全局路径(A* 输出,栅格坐标→物理坐标)=====
std::vector<std::pair<int,int>> globalPath;
int pathIdx = 0;
// ===== 机器人状态 =====
float robotX = 0, robotY = 0, robotYaw = 0;
// ===== DWA 参数 =====
const float MAX_V = 0.5; // m/s
const float MAX_W = 1.5; // rad/s
const float ACC_V = 0.3; // m/s²
const float ACC_W = 0.8; // rad/s²
const float DT = 0.05; // 控制周期 50ms
const int SAMPLES_V = 5;
const int SAMPLES_W = 7;
const float CELL_SIZE = 0.3; // 栅格边长 m
const float WHEEL_BASE = 0.25;
void setup() {
Serial.begin(115200);
// 电机初始化(速度模式)
motorL.linkSensor(&encL); motorL.linkDriver(&driverL);
motorL.controller = MotionControlType::velocity;
motorL.PID_velocity.P = 0.5; motorL.PID_velocity.I = 5.0;
motorL.init(); motorL.initFOC();
motorR.linkSensor(&encR); motorR.linkDriver(&driverR);
motorR.controller = MotionControlType::velocity;
motorR.PID_velocity.P = 0.5; motorR.PID_velocity.I = 5.0;
motorR.init(); motorR.initFOC();
// TODO: 加载地图,调用 A* 生成 globalPath
// globalPath = improvedAStar(startX, startY, goalX, goalY);
}
// DWA 轨迹评分(朝向 + 距离 + 速度)
float evaluateTrajectory(float v, float w, float tx, float ty) {
// 简化的评分:预测位置与目标点的接近程度
float predX = robotX + v * cos(robotYaw) * DT;
float predY = robotY + v * sin(robotYaw) * DT;
float predYaw = robotYaw + w * DT;
float distScore = -sqrt(pow(predX - tx, 2) + pow(predY - ty, 2));
float headingScore = cos(predYaw - atan2(ty - robotY, tx - robotX));
return headingScore * 0.7 + distScore * 0.3;
}
void loop() {
motorL.loopFOC();
motorR.loopFOC();
if (pathIdx >= (int)globalPath.size()) {
motorL.move(0); motorR.move(0);
return;
}
auto target = globalPath[pathIdx];
float targetX = target.first * CELL_SIZE;
float targetY = target.second * CELL_SIZE;
float dist = sqrt(pow(targetX - robotX, 2) + pow(targetY - robotY, 2));
if (dist < 0.15) { pathIdx++; return; }
// DWA 速度采样
float bestV = 0, bestW = 0, bestScore = -1e9;
float minV = max(0.0, 0.0 - ACC_V * DT);
float maxV = min(MAX_V, 0.0 + ACC_V * DT);
float minW = max(-MAX_W, 0.0 - ACC_W * DT);
float maxW = min(MAX_W, 0.0 + ACC_W * DT);
for (int i = 0; i < SAMPLES_V; i++) {
float v = minV + i * (maxV - minV) / (SAMPLES_V - 1);
for (int j = 0; j < SAMPLES_W; j++) {
float w = minW + j * (maxW - minW) / (SAMPLES_W - 1);
float score = evaluateTrajectory(v, w, targetX, targetY);
if (score > bestScore) {
bestScore = score; bestV = v; bestW = w;
}
}
}
// 差速解算
motorL.move(bestV - bestW * WHEEL_BASE / 2);
motorR.move(bestV + bestW * WHEEL_BASE / 2);
// 里程计更新
robotX += bestV * cos(robotYaw) * DT;
robotY += bestV * sin(robotYaw) * DT;
robotYaw += bestW * DT;
delay(50);
}
来源:该结构参考了农田避障机器人中改进 A* 全局路径与 DWA 局部速度采样的组合方案 。
2、滚动窗口 A* 动态重规划(迷宫/动态环境)
每 N 步以机器人为中心截取滚动窗口重新规划,用局部 5×5 窗口代替全局 20×20 地图,平衡算力与响应速度。
#include <SimpleFOC.h>
#include <vector>
// ===== 电机对象(从略,同案例一)=====
BLDCMotor motorL(7);
BLDCMotor motorR(7);
// ===== 全局地图与滚动窗口 =====
const int MAP_W = 20, MAP_H = 20;
const int WIN_SIZE = 5; // 滚动窗口边长(栅格数)
int gridMap[MAP_W][MAP_H]; // 0=自由 1=障碍
std::vector<std::pair<int,int>> localPath;
int robotGX = 10, robotGY = 10;
int goalGX = 15, goalGY = 15;
// ===== 重规划周期 =====
const int REPLAN_INTERVAL = 5; // 每5步重规划一次
int stepCount = 0;
void setup() {
Serial.begin(115200);
// ... 电机初始化从略 ...
}
// 简化 A*(四邻域,曼哈顿启发)
std::vector<std::pair<int,int>> aStarLocal(int sx, int sy, int ex, int ey) {
// 在 WIN_SIZE×WIN_SIZE 窗口内搜索
// 返回局部路径(栅格坐标)
std::vector<std::pair<int,int>> path;
// TODO: 实现轻量 A*,节点结构仅存 x,y,parent
return path;
}
void loop() {
motorL.loopFOC();
motorR.loopFOC();
// 每 REPLAN_INTERVAL 步触发一次重规划
if (stepCount % REPLAN_INTERVAL == 0 || localPath.empty()) {
// 截取以机器人为中心的滚动窗口
int winStartX = constrain(robotGX - WIN_SIZE/2, 0, MAP_W - WIN_SIZE);
int winStartY = constrain(robotGY - WIN_SIZE/2, 0, MAP_H - WIN_SIZE);
// 将窗口内障碍物复制到局部地图(简化:直接访问全局 map 的窗口区域)
// 在窗口坐标系下执行 A*
localPath = aStarLocal(robotGX, robotGY, goalGX, goalGY);
Serial.print("[重规划] 窗口起点: ");
Serial.print(winStartX); Serial.print(","); Serial.println(winStartY);
}
// 跟踪局部路径第一个点
if (!localPath.empty()) {
auto [tx, ty] = localPath[0];
float targetX = tx * 0.3; // 栅格→米
float targetY = ty * 0.3;
// TODO: moveTo(targetX, targetY) —— 差速控制代码从略
float dist = sqrt(pow(targetX - robotGX * 0.3, 2) +
pow(targetY - robotGY * 0.3, 2));
if (dist < 0.1) {
localPath.erase(localPath.begin());
robotGX = tx;
robotGY = ty;
}
}
stepCount++;
delay(20);
}
来源:滚动窗口重规划策略参考了动态迷宫环境中“每 5 步重规划一次,局部失败触发全局重规划”的设计 。
3、分层 A* + 动态障碍绕行(大型迷宫/仓储)
顶层稀疏地图(10×10,1.5m/格)规划粗路径,底层稠密地图(5×5,0.3m/格)细化并处理动态障碍。
#include <SimpleFOC.h>
#include <vector>
// ===== 双电机 =====
BLDCMotor motorL(7), motorR(7);
// ===== 双层地图 =====
const int TOP_W = 10, TOP_H = 10; // 顶层稀疏
const int BOT_W = 5, BOT_H = 5; // 底层稠密
int topGrid[TOP_W][TOP_H];
int botGrid[BOT_W][BOT_H];
// ===== 路径 =====
std::vector<std::pair<int,int>> topPath;
std::vector<std::pair<int,int>> botPath;
int topIndex = 0, botIndex = 0;
// ===== 动态障碍 =====
struct DynObs { int x, y, lifetime; };
std::vector<DynObs> dynObsList;
// ===== 超声波引脚 =====
#define TRIG_F 12
#define ECHO_F 13
float readCM(int trig, int echo) {
digitalWrite(trig, LOW); delayMicroseconds(2);
digitalWrite(trig, HIGH); delayMicroseconds(10);
digitalWrite(trig, LOW);
return pulseIn(echo, HIGH) * 0.034 / 2;
}
void setup() {
Serial.begin(115200);
pinMode(TRIG_F, OUTPUT); pinMode(ECHO_F, INPUT);
// ... 电机初始化从略 ...
}
// 顶层 A*(稀疏地图)
std::vector<std::pair<int,int>> aStarTop(int sx, int sy, int ex, int ey) {
// TODO: 在 TOP_W×TOP_H 上执行 A*
return {};
}
// 底层 A*(稠密地图,含动态障碍)
std::vector<std::pair<int,int>> aStarBot(int sx, int sy, int ex, int ey) {
// TODO: 在 BOT_W×BOT_H 上执行 A*,访问 botGrid 时将动态障碍标记为 1
return {};
}
void handleDynamicObstacle() {
float dF = readCM(TRIG_F, ECHO_F);
if (dF < 20 && dF > 0) {
// 将前方障碍映射到栅格坐标
int bx = 0, by = 0; // TODO: 根据机器人位姿计算
// 更新底层地图
botGrid[bx % BOT_W][by % BOT_H] = 1;
dynObsList.push_back({bx, by, 50}); // 50帧后过期
botPath.clear(); // 触发底层重规划
Serial.println("[避障] 动态障碍触发底层重规划");
}
}
void loop() {
motorL.loopFOC();
motorR.loopFOC();
// 顶层路径推进
if (topPath.empty() || topIndex >= (int)topPath.size()) {
// TODO: 重新规划顶层路径
}
// 底层细化
if (botPath.empty()) {
auto [topTx, topTy] = topPath[topIndex];
// 将顶层节点映射到底层目标
botPath = aStarBot(0, 0, topTx % BOT_W, topTy % BOT_H);
}
handleDynamicObstacle();
// 跟踪底层路径
if (!botPath.empty()) {
auto [tx, ty] = botPath[0];
// TODO: 差速控制到 (tx, ty)
}
delay(20);
}
来源:分层 A* 与动态障碍绕行思路参考了“顶层稀疏规划 + 底层稠密细化 + 动态障碍触发局部绕行”的分层架构 。
要点解读
-
A 在 Arduino 上的核心矛盾是内存,不是算法本身*
Arduino Uno 仅有 2KB SRAM,标准 A* 的开放列表/关闭列表用动态指针极易耗尽内存。可行的策略包括:用 byte 数组存储节点索引代替指针;地图用 PROGMEM 存入 Flash;或干脆省略 G 值、退化为贪心最佳优先搜索(F=H),牺牲最优性换取可行性 。案例一中的路径点用 std::pair 存储虽可读性好,但在 Uno 上需严格控制路径长度。 -
全局规划与局部执行必须解耦
A* 输出的是“航点序列”,电机控制跟踪的是“瞬时速度/角速度”。中间需要一层转换:路径点到达判定(如 dist < 0.15)→ 切换下一个航点。案例一中 DWA 的角色就是这层“翻译器”——它不修改全局路径,只负责在当前路径段附近采样出可执行的速度指令 。 -
动态障碍处理靠“重规划频率”而非“算法复杂度”
在 Arduino 上实现实时全图重规划不现实。案例二和案例三的策略是:限制重规划频率(每 5 步或每 500ms),缩小搜索范围(滚动窗口或分层细化)。动态障碍只需触发局部重规划,顶层粗路径保持不变 。这样既避免了算力爆炸,又保证了响应性。 -
SimpleFOC 的速度模式是路径跟踪的天然搭档
路径规划输出的目标通常需要转换为左右轮速度。SimpleFOC 的 MotionControlType::velocity 模式内置 PID 速度环,左右电机各设一个 BLDCMotor 对象,接收差速解算后的目标值即可 。案例一中的 motorL.move(v - wL/2) 和 motorR.move(v + wL/2) 就是这一组合的最小实现。 -
地图坐标系与机器人坐标系的映射是最容易出错的地方
栅格坐标 (gx, gy) 到物理坐标 (x, y) 的转换依赖 CELL_SIZE;机器人的里程计更新依赖 v 和 w 的积分。案例二中 robotGX = tx 的赋值只有在机器人精确到达该栅格中心时才成立,实际项目中必须用编码器里程计做闭环修正。建议初期在 moveTo 中加入“到达容差”判断,避免因里程计漂移导致路径点永远无法被消费 。

4、A*全局路径规划+手动地图标定+电机执行
适用场景:已知室内/室外消防场景地图,需沿规划路径直行、转向,无动态障碍物。
// 栅格地图:0为可通行,1为障碍物
const int MAP_SIZE = 50;
uint8_t grid_map[MAP_SIZE][MAP_SIZE] = {0};
struct Position{ int x; int y; };
// A* 节点结构
struct Node{
Position pos;
int g, f;
Node* parent;
// 重载小于号,用于优先队列
bool operator<(const Node& other) const { return f > other.f; }
};
// 启发函数:曼哈顿距离
int heuristic(const Position& a, const Position& b){
return abs(a.x - b.x) + abs(a.y - b.y);
}
// A* 路径规划函数
std::vector<Position> astar_plan(Position start, Position goal){
std::priority_queue<Node> open_set;
bool closed[MAP_SIZE][MAP_SIZE] = {false};
int g_score[MAP_SIZE][MAP_SIZE];
memset(g_score, 0x3f, sizeof(g_score));
Node start_node = {start, 0, heuristic(start, goal), nullptr};
g_score[start.x][start.y] = 0;
open_set.push(start_node);
while(!open_set.empty()){
Node current = open_set.top();
open_set.pop();
if(closed[current.pos.x][current.pos.y]) continue;
closed[current.pos.x][current.pos.y] = true;
if(current.pos.x == goal.x && current.pos.y == goal.y){
std::vector<Position> path;
while(current.parent != nullptr){
path.push_back(current.pos);
current = *current.parent;
}
path.push_back(start);
reverse(path.begin(), path.end());
return path;
}
// 遍历四邻域
int dx[] = {-1,1,0,0};
int dy[] = {0,0,-1,1};
for(int i=0; i<4; i++){
int nx = current.pos.x + dx[i];
int ny = current.pos.y + dy[i];
if(nx<0 || nx>=MAP_SIZE || ny<0 || ny>=MAP_SIZE || grid_map[nx][ny]==1) continue;
int new_g = g_score[current.pos.x][current.pos.y] + 1;
if(new_g < g_score[nx][ny]){
g_score[nx][ny] = new_g;
Node next = {{nx,ny}, new_g, new_g + heuristic({nx,ny}, goal), ¤t};
open_set.push(next);
}
}
}
return {}; // 路径不存在
}
#include <SimpleFOC.h>
SimpleFOCMotor2 motorL = SimpleFOCMotor2(8,9,10,A2,A3);
SimpleFOCMotor2 motorR = SimpleFOCMotor2(5,6,11,A0,A1);
float target_speed_L = 0, target_speed_R = 0;
Position robot_pos = {5,5}; // 机器人初始栅格坐标
Position goal_pos = {40,40};
const float GRID_SIZE = 0.5f; // 单个栅格对应实际物理长度,单位m
void setup(){
Serial.begin(9600);
motorL.init(); motorR.init();
motorL.controller = FOC_VELOCITY; motorR.controller = FOC_VELOCITY;
// 初始化地图障碍物
for(int i=20;i<=30;i++) grid_map[i][20] = 1;
}
void loop(){
if(robot_pos.x==goal_pos.x && robot_pos.y==goal_pos.y){
motorL.setVoltage(0); motorR.setVoltage(0);
return;
}
// 每50个控制周期规划一次路径
static unsigned long last_plan_time = 0;
if(millis()-last_plan_time > 50){
std::vector<Position> path = astar_plan(robot_pos, goal_pos);
last_plan_time = millis();
}
// 简化执行:根据方向调整电机差速
Position next = robot_pos; // 实际中需从路径栈获取下一个点
if(next.x > robot_pos.x){ // 向右直行
target_speed_L = 120; target_speed_R = 120;
} else if(next.x < robot_pos.x){ // 向左直行
target_speed_L = 120; target_speed_R = 120;
} else if(next.y > robot_pos.y){ // 向前直行
target_speed_L = 120; target_speed_R = 120;
} else if(next.y < robot_pos.y){ // 向后直行
target_speed_L = -120; target_speed_R = -120;
}
// PID控制电机
float uL = 1.0f * id(target_speed_L - motorL.shaft_velocity);
float uR = 1.0f * id(target_speed_R - motorR.shaft_velocity);
motorL.setVoltage(constrain(uL,-8,8));
motorR.setVoltage(constrain(uR,-8,8));
}
5、带运动学约束的A*路径平滑+电机跟踪控制
适用场景:对转弯平顺性要求高的场景,避免直角转弯卡顿,需将栅格路径平滑为符合运动学约束的轨迹。
#include <SimpleFOC.h>
const int MAP_SIZE = 50;
uint8_t grid_map[MAP_SIZE][MAP_SIZE] = {0};
struct Position{ int x; int y; };
// 基础A*规划函数(同案例1,此处省略)
std::vector<Position> astar_plan(Position start, Position goal){
// 实现同案例4的A*算法,返回栅格点路径
return {};
}
// Birch-Weiler路径平滑:将栅格路径转为圆角折线
std::vector<float> smooth_path(std::vector<Position>& raw_path){
std::vector<float> smoothed;
if(raw_path.size() < 3) return raw_path;
smoothed.push_back(raw_path[0].x * GRID_SIZE);
smoothed.push_back(raw_path[0].y * GRID_SIZE);
for(int i=1; i<raw_path.size()-1; i++){
Position prev = raw_path[i-1];
Position cur = raw_path[i];
Position next = raw_path[i+1];
// 检测到转折点时,插入圆角中间点
if((prev.x!=cur.x && cur.y!=next.y) || (prev.y!=cur.y && cur.x!=next.x)){
// 计算圆角半径(根据机器人转弯半径)
float radius = 0.3f;
float mid_x = cur.x * GRID_SIZE;
float mid_y = cur.y * GRID_SIZE;
// 插入两个圆角过渡点
smoothed.push_back(mid_x - radius);
smoothed.push_back(mid_y);
smoothed.push_back(mid_x);
smoothed.push_back(mid_y - radius);
}
}
int last = raw_path.size()-1;
smoothed.push_back(raw_path[last].x * GRID_SIZE);
smoothed.push_back(raw_path[last].y * GRID_SIZE);
return smoothed;
}
#include <SimpleFOC.h>
SimpleFOCMotor2 motorL = SimpleFOCMotor2(8,9,10,A2,A3);
SimpleFOCMotor2 motorR = SimpleFOCMotor2(5,6,11,A0,A1);
float robot_x = 0.0f, robot_y = 0.0f, theta = 0.0f; // 机器人位姿
std::vector<float> current_path; // 平滑后的路径点
int path_index = 0;
const float WHEEL_BASE = 0.5f; // 轮距,单位m
const float GRID_SIZE = 0.5f;
// 差速机器人运动学:计算目标角速度和线速度
void motion_control(float target_x, float target_y){
float dx = target_x - robot_x;
float dy = target_y - robot_y;
float target_theta = atan2f(dy, dx);
float theta_error = target_theta - theta;
// 归一化角度
if(theta_error > M_PI) theta_error -= 2*M_PI;
if(theta_error < -M_PI) theta_error += 2*M_PI;
// 样条插值:平滑速度,避免突变
static float cur_v = 0, cur_w = 0;
float target_v = 0.5f; // 最大线速度,m/s
float target_w = 1.0f * theta_error; // 角速度与误差正相关
if(abs(theta_error) < 0.1f) target_v = 0.8f; // 朝向误差小,加速
else target_v = 0.2f; // 朝向误差大,减速
cur_v += 0.1f * (target_v - cur_v);
cur_w += 0.1f * (target_w - cur_w);
// 差速转单轮转速(RPM转m/s需乘系数,此处简化)
target_speed_L = (cur_v - cur_w * WHEEL_BASE/2) * 100;
target_speed_R = (cur_v + cur_w * WHEEL_BASE/2) * 100;
// PID控制电机
float uL = 1.0f * id(target_speed_L - motorL.shaft_velocity);
float uR = 1.0f * id(target_speed_R - motorR.shaft_velocity);
motorL.setVoltage(constrain(uL,-8,8));
motorR.setVoltage(constrain(uR,-8,8));
}
void setup(){
Serial.begin(9600);
motorL.init(); motorR.init();
motorL.controller = FOC_VELOCITY; motorR.controller = FOC_VELOCITY;
}
void loop(){
if(path_index >= current_path.size()){
motorL.setVoltage(0); motorR.setVoltage(0);
return;
}
motion_control(current_path[path_index], current_path[path_index+1]);
// 简化位姿更新,实际需结合里程计
float dt = 0.001f;
robot_x += cos(theta) * 0.1f * dt;
robot_y += sin(theta) * 0.1f * dt;
float speedL = motorL.shaft_velocity / 100.0f;
float speedR = motorR.shaft_velocity / 100.0f;
theta += (speedR - speedL) / WHEEL_BASE * dt;
// 到达目标点后切换下一个路径点
float dx = current_path[path_index] - robot_x;
float dy = current_path[path_index+1] - robot_y;
if(sqrtf(dx*dx + dy*dy) < 0.1f) path_index += 2;
}
6、动态重规划+速度自适应+电机抗扰控制
适用场景:消防场景存在动态障碍物,需实时调整路径,转弯减速、直道加速,应对路面扰动。
#include <SimpleFOC.h>
const int MAP_SIZE = 50;
uint8_t grid_map[MAP_SIZE][MAP_SIZE] = {0};
struct Position{ int x; int y; };
// 动态障碍物列表
std::vector<Position> dynamic_obs;
// A*动态重规划:加入动态障碍物判断
std::vector<Position> dynamic_astar(Position start, Position goal){
// 基础A*,遍历邻域时跳过临时动态障碍物
for(Position obs: dynamic_obs){
if(obs.x>=0 && obs.x<MAP_SIZE && obs.y>=0 && obs.y<MAP_SIZE)
grid_map[obs.x][obs.y] = 1;
}
std::vector<Position> path = astar_plan(start, goal);
// 清除临时障碍物
for(Position obs: dynamic_obs){
if(obs.x>=0 && obs.x<MAP_SIZE && obs.y>=0 && obs.y<MAP_SIZE)
grid_map[obs.x][obs.y] = 0;
}
return path;
}
#include <SimpleFOC.h>
SimpleFOCMotor2 motorL = SimpleFOCMotor2(8,9,10,A2,A3);
SimpleFOCMotor2 motorR = SimpleFOCMotor2(5,6,11,A0,A1);
Position robot_pos = {5,5};
Position goal_pos = {40,40};
std::vector<Position> current_path;
int path_index = 0;
float target_speed_L = 0, target_speed_R = 0;
const float MAX_SPEED = 180.0f; // 直道最大速度
const float MIN_SPEED = 60.0f; // 转弯最小速度
const float TURN_RADIUS = 0.3f;
const float GRID_SIZE = 0.5f;
void speed_adapt(float theta_error){
// 根据转弯角度自适应调整速度
float speed_ratio = 1.0f - min(abs(theta_error)/M_PI, 0.8f);
float base_speed = MAX_SPEED * speed_ratio + MIN_SPEED * (1 - speed_ratio);
target_speed_L = base_speed;
target_speed_R = base_speed;
// 差速转向
float turn_speed = 100.0f * (theta_error > 0 ? -1 : 1);
target_speed_L += turn_speed;
target_speed_R -= turn_speed;
}
void loop(){
static unsigned long last_plan_time = 0;
// 每秒重规划一次,处理动态障碍物
if(millis() - last_plan_time > 1000){
current_path = dynamic_astar(robot_pos, goal_pos);
path_index = 0;
last_plan_time = millis();
}
if(path_index >= current_path.size()){
motorL.setVoltage(0); motorR.setVoltage(0);
return;
}
Position next = current_path[path_index];
// 计算朝向误差
float dx = (next.x - robot_pos.x) * GRID_SIZE;
float dy = (next.y - robot_pos.y) * GRID_SIZE;
float target_theta = atan2f(dy, dx);
float theta_error = target_theta - theta;
if(theta_error > M_PI) theta_error -= 2*M_PI;
if(theta_error < -M_PI) theta_error += 2*M_PI;
// 速度自适应
speed_adapt(theta_error);
// 抗扰PID控制
float kp = 1.0f, ki = 0.05f, kd = 0.1f;
float errorL = target_speed_L - motorL.shaft_velocity;
float errorR = target_speed_R - motorR.shaft_velocity;
float uL = kp*errorL + ki*id(errorL) + kd*id(errorL);
float uR = kp*errorR + ki*id(errorR) + kd*id(errorR);
motorL.setVoltage(constrain(uL,-8,8));
motorR.setVoltage(constrain(uR,-8,8));
// 位姿更新与路径点切换(同案例5简化实现)
// ...
}
要点解读
栅格地图的分辨率与标定精度直接决定规划精度
地图分辨率需与机器人尺寸、运动控制精度匹配,过粗无法识别小障碍物,过细则计算量超出Arduino性能上限;需将栅格坐标与实际物理坐标(米)严格标定,否则路径跟踪偏差会持续累积。
A规划需加入运动学约束或后置平滑处理
原生A规划的是栅格中心点最短路径,存在直角拐弯,不符合机器人转弯半径约束;需通过Birch-Weiler、多项式插值等方式平滑路径,生成符合运动学约束的连续轨迹,避免电机堵转或打滑。
路径跟踪需采用速度/角速度的分级闭环控制
先通过路径期望位姿计算目标线速度与角速度,再将速度分配到左右电机形成闭环;同时需加入角度误差的归一化处理,避免跨±π时控制反转,保证转向逻辑稳定。
动态场景需规律触发重规划,平衡实时性与算力
Arduino算力有限,重规划频率需控制在0.5-1s一次,避免频繁规划占用过多资源;同时采用临时障碍物标记方式,不修改全局地图,兼顾规划效率与环境适应性。
速度策略需匹配路径曲率,实现加减速平稳过渡
直道部分采用最大速度提升效率,转弯部分根据曲率/角度误差降低速度,甚至加入速度前瞻(Look-ahead)控制,提前减速;同时电机PID需加入抗扰项,应对路面湿滑、负载突变等干扰,保证路径跟踪精度。
请注意:以上案例仅作为思路拓展的参考示例,不保证完全正确、适配所有场景或可直接编译运行。由于硬件平台、实际使用场景、Arduino 版本的差异,均可能影响代码的适配性与使用方法的选择。在实际编程开发时,请务必根据自身硬件配置、使用场景及具体功能需求进行针对性调整,并通过多次实测验证效果;同时需确保硬件接线正确,充分了解所用传感器、执行器等设备的技术规范与核心特性。对于涉及硬件操作的代码,使用前务必核对引脚定义、电平参数等关键信息的准确性与安全性,避免因参数错误导致硬件损坏或运行异常。

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐

所有评论(0)