// 引腳定義
const int STEP_PIN = 2; // D2 (PA10) 控制步進脈衝
const int DIR_PIN = 3; // D3 (PB3) 控制旋轉方向
const int POT_PIN = A0; // A0 (PA0) 讀取可變電阻類比電壓
// NEMA 17 標準全步進為 200 步/圈 (一步 1.8 度)
const int STEPS_PER_REV = 200;
int currentStep = 0; // 記錄馬達當前位置 (0 ~ 199 步)
void setup() {
Serial.begin(115200);
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
pinMode(POT_PIN, INPUT);
Serial.println("STM32 NUCLEO-C031C6 + A4988 + Potentiometer Ready!");
}
void loop() {
// 1. 讀取可變電阻類比數值 (0 ~ 1023)
int potValue = analogRead(POT_PIN);
// 2. 將 0~1023 映射為目標步數 (0 ~ 199 步,對應 0° ~ 358.2°)
int targetStep = map(potValue, 0, 1023, 0, STEPS_PER_REV - 1);
// 3. 當目標步數與目前步數不一致時,持續發送脈衝微幅追隨
if (targetStep != currentStep) {
// 判斷移動方向並設定 DIR 腳位
if (targetStep > currentStep) {
digitalWrite(DIR_PIN, HIGH); // 順時針
currentStep++;
} else {
digitalWrite(DIR_PIN, LOW); // 逆時針
currentStep--;
}
// 發送單一方波脈衝 (STEP)
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(STEP_PIN, LOW);
// 控制馬達追隨轉動時的速度 (脈衝間隔 2000µs)
delayMicroseconds(2000);
// 印出目前位置與對應角度
Serial.print("Pot ADC: ");
Serial.print(potValue);
Serial.print(" | Step: ");
Serial.print(currentStep);
Serial.print(" | Angle: ");
Serial.print(currentStep * 1.8);
Serial.println(" deg");
}
delay(1); // 輕微延遲維持系統穩定
}