Clamp speed

This commit is contained in:
2026-07-07 14:11:06 +08:00
parent ff9da87a23
commit 6e490ed822
@@ -18,13 +18,17 @@ int stepSequence[4][4] = {
const int STEPS_PER_REVOLUTION = 2048; // 28BYJ-48 standard (512 steps * 4 gear reduction)
const float DEGREES_PER_STEP = 360.0 / STEPS_PER_REVOLUTION;
// Speed Limits (Clamping)
const float MAX_TURN_SPEED = 45.0; // Maximum safe speed in deg/s
const float MIN_TURN_SPEED = 0.1; // Minimum safe speed to avoid div by zero
// --- Global Variables ---
enum State { MOVE, WAIT };
enum Mode { AUTO, MANUAL };
Mode autoMode = AUTO; // Default: AUTO
float targetAngle = 0.0; // Target angle in degrees
float turnSpeed = 5.0; // Speed in degrees per second
float targetAngle = 15.0; // Target angle in degrees
float turnSpeed = 45.0; // Speed in degrees per second
State _currState = MOVE; // Default: MOVE
@@ -49,10 +53,6 @@ void setStep(int a, int b, int c, int d) {
}
void updateStepInterval() {
if (turnSpeed <= 0) {
_stepInterval = 0.1; // Fallback to avoid div by zero
return;
}
// Calculate steps per second: speed / degrees_per_step
float stepsPerSecond = turnSpeed / DEGREES_PER_STEP;
_stepInterval = 1.0 / stepsPerSecond; // Seconds per step
@@ -157,12 +157,15 @@ void setup() {
_waitTime = millis();
// Initial calculation (move 0 degrees to set defaults)
calculateStepsForAngle(0.0);
// Ensure we start in MOVE if we want immediate action, or WAIT if idle
// Based on your logic: "initialized in MOVE state"
calculateStepsForAngle(targetAngle);
_currState = MOVE;
Serial.println("Ready. Commands: m[0|1], a[deg], s[deg/s], i[sec]");
Serial.println(" (Speed clamped between ");
Serial.print(MIN_TURN_SPEED);
Serial.print(" and ");
Serial.print(MAX_TURN_SPEED);
Serial.println(" deg/s)");
printStatus();
}
@@ -224,10 +227,11 @@ void loop() {
printError("Invalid angle format.");
} else {
calculateStepsForAngle(angle);
targetAngle = angle;
Serial.print(" -> Moving ");
Serial.print(_stepCount);
Serial.print(" steps (");
Serial.print(angle);
Serial.print(targetAngle);
Serial.println(" degrees).");
if (_stepCount == 0) {
Serial.println(" -> No movement required (0 degrees).");
@@ -244,6 +248,17 @@ void loop() {
printError("Invalid speed. Must be > 0.");
} else {
turnSpeed = speed;
// Logic to check if clamping occurred
float actualSpeed = turnSpeed;
if (actualSpeed > MAX_TURN_SPEED) {
turnSpeed = MAX_TURN_SPEED;
Serial.print(" -> WARNING: Speed clamped to max ");
} else if (actualSpeed < MIN_TURN_SPEED) {
turnSpeed = MIN_TURN_SPEED;
Serial.print(" -> WARNING: Speed clamped to min ");
}
updateStepInterval();
Serial.print(" -> Speed set to ");
Serial.print(turnSpeed);