class StepperMotor {
private:
int pinEnable, pinStep, pinDirection;
int stepsPerRevolution;
public:
StepperMotor(int enablePin, int stepPin, int directionPin, int stepsPerRev = 200) {
pinEnable = enablePin;
pinStep = stepPin;
pinDirection = directionPin;
stepsPerRevolution = stepsPerRev;
pinMode(pinEnable, OUTPUT);
pinMode(pinStep, OUTPUT);
pinMode(pinDirection, OUTPUT);
digitalWrite(pinEnable, HIGH); // A4988: HIGH = disabilitato inizialmente
digitalWrite(pinStep, LOW);
digitalWrite(pinDirection, LOW);
}
void enableMotor() {
digitalWrite(pinEnable, LOW); // A4988: LOW = abilitato
}
void disableMotor() {
digitalWrite(pinEnable, HIGH); // A4988: HIGH = disabilitato
}
void setDirection(bool clockwise) {
digitalWrite(pinDirection, clockwise ? HIGH : LOW);
}
void stepMotor(int steps, int delayMs = 10) {
enableMotor();
delay(1); // Piccola pausa per stabilizzare l'enable
for (int i = 0; i < abs(steps); i++) {
digitalWrite(pinStep, HIGH);
delay(delayMs);
digitalWrite(pinStep, LOW);
delay(delayMs);
}
}
void rotateRevolutions(float revolutions, int speedDelay = 10) {
int steps = (int)(abs(revolutions) * stepsPerRevolution);
setDirection(revolutions > 0);
stepMotor(steps, speedDelay);
}
void rotateDegrees(float degrees, int speedDelay = 10) {
int steps = (int)(abs(degrees) * stepsPerRevolution / 360.0);
setDirection(degrees > 0);
stepMotor(steps, speedDelay);
}
};
// Configurazione pin
const int ENABLE_PIN = 4;
const int STEP_PIN = 15;
const int DIRECTION_PIN = 2;
const int STEPS_PER_REVOLUTION = 200;
// Istanza del motore
StepperMotor motor(ENABLE_PIN, STEP_PIN, DIRECTION_PIN, STEPS_PER_REVOLUTION);
void setup() {
Serial.begin(115200);
}
void loop() {
Serial.println("Rotazione oraria completa...");
motor.rotateRevolutions(1, 5);
delay(1000);
Serial.println("Rotazione antioraria completa...");
motor.rotateRevolutions(-1, 5);
delay(1000);
Serial.println("Rotazione 90° orari...");
motor.rotateDegrees(90, 8);
delay(1000);
Serial.println("Rotazione 90° antiorari...");
motor.rotateDegrees(-90, 8);
delay(1000);
Serial.println("Rotazione veloce oraria...");
motor.rotateRevolutions(1, 3);
delay(1000);
Serial.println("Rotazione veloce antioraria...");
motor.rotateRevolutions(-1, 3);
delay(2000);
Serial.println("Sequenza completata. Ripetizione...\n");
motor.disableMotor();
delay(1000);
}