// https://wokwi.com/projects/364535266637057025
// for https://forum.arduino.cc/t/stepper-motor-control-using-millis/1126030
// Example sketch to control a stepper motor with TB6600 stepper motor driver and Arduino without a library: number of revolutions, speed and direction.
// Define stepper motor connections and steps per revolution:
#define dirPin 2
#define stepPin 3
#define stepsPerRevolution 6400UL
unsigned long previo1 = 0;
unsigned long previo2 = 0;
unsigned long current;
boolean estado1 = false;
boolean estado2 = false;
int velocidad; //speed
int desplazamiento = 50; //data en mm
unsigned long usPerStep = 187 * 2;
void setup() {
// Declare pins as output:
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
Serial.begin(115200);
}
unsigned long stepsToGo = 0;
int mode = 0;
void loop() {
if (stepsToGo == 0 ) { // setup new motion
if (mode == 0 ) {
Serial.print('H');
digitalWrite(dirPin, HIGH); //direction.
stepsToGo = desplazamiento * stepsPerRevolution;
mode = 1; // plan following motion
} else {
Serial.print("L");
digitalWrite(dirPin, LOW);//direction.
stepsToGo = desplazamiento * stepsPerRevolution;
mode = 0; // plan following motion
}
}
stepAsNeeded(usPerStep);
}
void stepAsNeeded(unsigned long interval) {
static unsigned long lastStepUs = 0;
unsigned long now = micros();
if (now - lastStepUs < interval || stepsToGo == 0) {
return;
}
// otherwise, take a step
digitalWrite(stepPin, HIGH);
lastStepUs = now;
--stepsToGo;
digitalWrite(stepPin, LOW);
}