// 腳位定義
const int STEP_PIN = 2; // D2 控制脈衝 (STEP)
const int DIR_PIN = 3; // D3 控制方向 (DIR)
// NEMA 17 全步進標準為 200 步/圈 (一步 1.8 度)
const int STEPS_PER_REV = 200;
/**
* 發送步進脈衝函數
* @param steps 轉動步數
* @param speedDelayUs 脈衝間隔時間(微秒),數值越小速度越快
* @param isClockwise 是否順時針旋轉 (true: 順時針, false: 逆時針)
*/
void stepMotor(int steps, int speedDelayUs, bool isClockwise) {
// 1. 設定旋轉方向
digitalWrite(DIR_PIN, isClockwise ? HIGH : LOW);
// 2. 循環發送方波脈衝
for (int i = 0; i < steps; i++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(10); // 方波高電位觸發寬度 (至少需要 1~2us)
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(speedDelayUs); // 決定脈衝頻率(即旋轉速度)
}
}
void setup() {
Serial.begin(115200);
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
Serial.println("STM32 NUCLEO-C031C6 + A4988 Stepper Test Started!");
delay(1000);
}
void loop() {
// 1. 順時針旋轉 1 圈 (200 步),較高速度 (間隔 1000 µs)
Serial.println("Rotating 1 Turn Clockwise (Fast)...");
stepMotor(STEPS_PER_REV, 1000, true);
delay(1000);
// 2. 逆時針旋轉 2 圈 (400 步),中等速度 (間隔 2000 µs)
Serial.println("Rotating 2 Turns Counter-Clockwise (Medium)...");
stepMotor(STEPS_PER_REV * 2, 2000, false);
delay(1000);
// 3. 順時針定位旋轉 90 度 (50 步),較慢速度 (間隔 3000 µs)
Serial.println("Rotating 90 Degrees Clockwise (Slow)...");
stepMotor(50, 3000, true);
delay(2000);
}