// Forum: https://forum.arduino.cc/t/stepper-motor-with-millis-micros/1099939
// This Wokwi project: https://wokwi.com/projects/358757303490537473
const int dirPinX = 18;
const int stepPinX = 19;
unsigned long previousMicros;
unsigned long currentMicros;
const unsigned long period = 500; // 500 microseconds
int pulseState = LOW; // default low
void setup()
{
pinMode(stepPinX, OUTPUT);
pinMode(dirPinX, OUTPUT);
digitalWrite(dirPinX, HIGH);
}
void loop()
{
stepX();
}
void stepX()
{
currentMicros = micros(); //get the current "time" (time since program start)
// A millis-timer that toggles the output
if (currentMicros - previousMicros >= period) //test whether period elapsed
{
previousMicros = currentMicros;
// toggle the pulseState
if( pulseState == LOW)
pulseState = HIGH;
else
pulseState = LOW;
digitalWrite(stepPinX, pulseState);
}
}