This commit is contained in:
玖叁 2024-12-19 19:48:52 +08:00
parent f8d617ad34
commit 1cce583841
1 changed files with 20 additions and 14 deletions

View File

@ -266,7 +266,7 @@ bool CarStorage::isMounted = false;
void setup() void setup()
{ {
// 初始化<EFBFBD><EFBFBD><EFBFBD> // 初始化
Serial.begin(115200); Serial.begin(115200);
// 初始化 BLE // 初始化 BLE
@ -323,13 +323,19 @@ void handleSerialPacket(uint8_t *packet, int length, BLECharacteristic &characte
if (!deviceConnected || length < 4) if (!deviceConnected || length < 4)
return; return;
uint8_t packetLength = packet[1]; // 获取长度 uint8_t packetLength = packet[1];
uint8_t cmd = packet[2]; // 获取指令 uint8_t cmd = packet[2];
uint8_t direction, speed, time, wheel, diffSpeed; uint8_t direction, speed, time, wheel, diffSpeed;
float distance; float distance;
uint8_t buffer[PACKET_MAX_LENGTH]; // 用于存储要发送的数据 uint8_t buffer[PACKET_MAX_LENGTH];
int bufferIndex = 0; int bufferIndex = 0;
// PID 相关变量声明移到这里
float Kp, Ki, Kd;
float targetSpeed, currentSpeed, lastError, integral;
unsigned long lastTime;
unsigned long startTime;
switch (cmd) switch (cmd)
{ {
case CMD_GET_BT_STATUS: case CMD_GET_BT_STATUS:
@ -466,16 +472,15 @@ void handleSerialPacket(uint8_t *packet, int length, BLECharacteristic &characte
Serial.println("CMD_DEMO_PID"); Serial.println("CMD_DEMO_PID");
// PID 参数 // PID 参数
float Kp = 2.0; Kp = 2.0;
float Ki = 0.5; Ki = 0.5;
float Kd = 0.1; Kd = 0.1;
// PID 变量 targetSpeed = 255;
float targetSpeed = 255; // 目标速度 currentSpeed = 0;
float currentSpeed = 0; // 当前速度 lastError = 0;
float lastError = 0; // 上一次误差 integral = 0;
float integral = 0; // 积分项 lastTime = millis();
unsigned long lastTime = millis();
// 加速阶段 - PID控制 // 加速阶段 - PID控制
while (millis() - lastTime < 2000) while (millis() - lastTime < 2000)
@ -536,7 +541,8 @@ void handleSerialPacket(uint8_t *packet, int length, BLECharacteristic &characte
// 第一段全速前进1秒 // 第一段全速前进1秒
currentSpeed = 255; currentSpeed = 255;
unsigned long startTime = millis(); startTime = millis();
// 第一段全速前进1秒
while (millis() - startTime < 1000) while (millis() - startTime < 1000)
{ {
motorControl('A', currentSpeed); motorControl('A', currentSpeed);