#include <AccelStepper.h>

// 定义步进电机引脚
#define MOTOR1_STEP_PIN 2
#define MOTOR1_DIR_PIN 3
#define MOTOR2_STEP_PIN 4
#define MOTOR2_DIR_PIN 5
#define MOTOR3_STEP_PIN 6
#define MOTOR3_DIR_PIN 7

// 定义按钮引脚
#define BUTTON1_PIN 8
#define BUTTON2_PIN 9
#define BUTTON3_PIN 10

// 创建步进电机对象
AccelStepper motor1(AccelStepper::FULL4WIRE, MOTOR1_STEP_PIN, MOTOR1_DIR_PIN);
AccelStepper motor2(AccelStepper::FULL4WIRE, MOTOR2_STEP_PIN, MOTOR2_DIR_PIN);
AccelStepper motor3(AccelStepper::FULL4WIRE, MOTOR3_STEP_PIN, MOTOR3_DIR_PIN);

void setup() {
  // 设置步进电机速度和加速度
  motor1.setMaxSpeed(1000.0);
  motor1.setAcceleration(500.0);
  motor2.setMaxSpeed(1000.0);
  motor2.setAcceleration(500.0);
  motor3.setMaxSpeed(1000.0);
  motor3.setAcceleration(500.0);

  // 设置按钮引脚为输入模式
  pinMode(BUTTON1_PIN, INPUT_PULLUP);
  pinMode(BUTTON2_PIN, INPUT_PULLUP);
  pinMode(BUTTON3_PIN, INPUT_PULLUP);
}

void loop() {
  // 检测按钮状态
  if (digitalRead(BUTTON1_PIN) == LOW) {
    rotateMotors(5, 90, 90);
    delay(2000);
    rotateMotors(0, -90, -90);
  }

  if (digitalRead(BUTTON2_PIN) == LOW) {
    rotateMotors(5, 180, 90);
    delay(2000);
    rotateMotors(0, -180, -90);
  }

  if (digitalRead(BUTTON3_PIN) == LOW) {
    rotateMotors(5, 270, 90);
    delay(2000);
    rotateMotors(0, -270, -90);
  }
}

void rotateMotors(int motor1Rotations, int motor2Angle, int motor3Angle) {
  // 设置步进电机目标位置
  motor1.moveTo(motor1Rotations * 200);
  motor2.moveTo(motor2Angle * 1.4222);
  motor3.moveTo(motor3Angle * 1.4222);

  // 使步进电机运动到目标位置
  while (motor1.distanceToGo() != 0 || motor2.distanceToGo() != 0 || motor3.distanceToGo() != 0) {
    motor1.run();
    motor2.run();
    motor3.run();
  }
}
A4988
A4988
A4988