/* Stepper Motor A4988 Driver with Serial Control */
int stepPin = 4; // STEP pin
int dirPin = 2; // DIR pin
uint16_t pulseTime = 50; // Default pulse time in ms
bool dirState = HIGH; // Default direction
void pulsedemo(uint16_t time) {
digitalWrite(stepPin, HIGH);
delay(time);
digitalWrite(stepPin, LOW);
delay(time);
}
void setup() {
pinMode(dirPin, OUTPUT);
pinMode(stepPin, OUTPUT);
digitalWrite(dirPin, dirState);
Serial.begin(9600);
Serial.println("Stepper Motor Controller Ready");
Serial.println("Commands:");
Serial.println(" 'H' - Set DIR pin HIGH");
Serial.println(" 'L' - Set DIR pin LOW");
Serial.println(" 'Txxx' - Set pulse time (e.g. T100 for 100ms)");
Serial.println(" 'Rxxx' - Run xxx steps (e.g. R200 for 200 steps)");
}
void loop() {
if (Serial.available() > 0) {
char command = Serial.read();
// Handle direction commands
if (command == 'H' || command == 'h') {
dirState = HIGH;
digitalWrite(dirPin, dirState);
Serial.println("Direction set to HIGH");
}
else if (command == 'L' || command == 'l') {
dirState = LOW;
digitalWrite(dirPin, dirState);
Serial.println("Direction set to LOW");
}
// Handle pulse time command (format: Txxx)
else if (command == 'T' || command == 't') {
delay(10); // Wait for rest of command
String timeStr = Serial.readStringUntil('\n');
timeStr.trim();
pulseTime = timeStr.toInt();
Serial.print("Pulse time set to: ");
Serial.print(pulseTime);
Serial.println("ms");
}
// Handle run command (format: Rxxx)
else if (command == 'R' || command == 'r') {
delay(10); // Wait for rest of command
String stepStr = Serial.readStringUntil('\n');
stepStr.trim();
int steps = stepStr.toInt();
if (steps > 0) {
Serial.print("Running ");
Serial.print(steps);
Serial.println(" steps...");
digitalWrite(dirPin, dirState);
for (int i = 0; i < steps; i++) {
pulsedemo(pulseTime);
}
Serial.println("Done");
}
}
}
}方向
顺时针-亮
逆时针-灭
闪烁频率
速度快慢