arduino来控制步进电机制作投球器

使用arduino来控制步进电机制作投球器,控制角度是0-180.求问这段代码还能继续优化的地方


#include <Stepper.h>

const int stepsPerRevolution = 2048;  // Number of steps per revolution of stepper motor
const int motorPin1 = 8;
const int motorPin2 = 9;
const int motorPin3 = 10;
const int motorPin4 = 11;

Stepper myStepper(stepsPerRevolution, motorPin1, motorPin2, motorPin3, motorPin4);

int targetAngle = 0;       // Target angle (0 to 180 degrees)
int targetRevolutions = 2; // Number of target laps

void setup() {
  Serial.begin(9600);  // Initialize Serial communication
  myStepper.setSpeed(60);
}

void loop() {
  if (Serial.available() > 0) {
    String input = Serial.readStringUntil('\n');  // Read the input command from Serial

    if (input.startsWith("angle:")) {
      int angleValue = input.substring(6).toInt();  // Extract the angle value from the input command

      if (angleValue >= 0 && angleValue <= 180) {
        targetAngle = angleValue;  // Set the target angle
        int targetSteps = map(targetAngle, 0, 180, 0, stepsPerRevolution);  // Map the angle to steps
        myStepper.step(targetSteps);
        delay(1000);
      } else {
        Serial.println("Invalid angle value. Angle must be between 0 and 180 degrees.");
      }
    } else if (input.startsWith("revolutions:")) {
      int revolutionsValue = input.substring(12).toInt();  // Extract the revolutions value from the input command

      if (revolutionsValue >= 1 && revolutionsValue <= 20) {
        targetRevolutions = revolutionsValue;  // Set the target revolutions
        int targetSteps = targetRevolutions * stepsPerRevolution;  // Calculate the target steps based on the revolutions
        myStepper.step(targetSteps);
        delay(1000);
      } else {
        Serial.println("Invalid revolutions value. Revolutions must be between 1 and 20.");
      }
    } else {
      Serial.println("Invalid command.");
    }
  }
}