I have a small dilemma. I have code that runs a stepper motor using the A4988 chip and I would like to use millis () instead of delay () as it interferes with the usb read. I would like to move 400 steps in one direction.
Here’s the code
steps = 400
for (int s = 0; s < steps; s++){
digitalWrite( STEP_PIN, HIGH);
delayMicroseconds (375);
digitalWrite( STEP_PIN, LOW);
delay (2);
}
Hello.
Since you are using delayMicroseconds()
, you should use micros()
instead of millis()
. Here is an example of how you could implement your delays without using the delay functions:
const byte STEP_PIN = 5;
int steps;
unsigned long time_a;
unsigned long time_b;
void setup() {
steps = 400;
}
void loop() {
for (int s = 0; s < steps; s++){
time_a = micros();
digitalWrite(STEP_PIN, HIGH);
while(micros() - time_a < 375){
// do nothing
}
time_b = micros();
digitalWrite(STEP_PIN, LOW);
while(micros() - time_b < 2000){
// do nothing
}
}
while(1);
}
-Jon
Thank you, Jonathan.
I was looking for non-blocking code and that is why I was thinking of using millis() instead of delays.
You might also look into this AccelStepper Arduino library, which supports non-blocking operations.
-Jon