I have effectively replicated the "no delay blink" example on my Arduino Mega2560 to send pulses to a stepper motor driver. I included a for loop to increment the number of "pulses" given to achieve a single rotation (800 pulses), then delay for a moment and repeat.
I find that the motor is only rotating a fraction of a revolution. It would seem that the micros() running faster than the for loop resulting in missed pulses. I would greatly appreciate if someone could point out why this may be, and how to work around it.
#include <Wire.h>
const int Pul_OUT = 9;
unsigned long previousMicros = 0;
unsigned long Pul_Interval = 100;
int setPosition = 800;
void setup()
{
pinMode(Pul_OUT, OUTPUT);
digitalWrite(Pul_OUT, LOW);
}
void loop()
{
no_delay_Position();
delay(100);
}
int no_delay_Position()
{
for (int i = setPosition; i >= 0 ; i--)
{
unsigned long currentMicros = micros();
if (currentMicros - previousMicros > Pul_Interval)
{
previousMicros = currentMicros;
PulState = !PulState;
digitalWrite(Pul_OUT, PulState);
}
}
}