Hello,
I have a litte project that sends instructions to a stepper motor. The motor turns a wheel that has a position switch to find the starting position. I want to find the starting positon, move 325 steps, pause there and then go on to other positions.
Without the delay, it works fine. It finds the starting position, and moves the additional 325 steps seamlessly. But when I insert the delay it is like the code executes the delay first, before moving the 325 steps.
I have also tried using milllis() like in "blink without delay", with the same result.
I really don't understand what's wrong. Pleased for any help.
-Dan.
I've inserted the bit of code that is not cooperating below.
...
if(!debouncerRightButton.read()) { // Run sequence
while(debouncerRotSwitch.read()) { // Run until switch on wheel is hit (0 position)
debouncerRotSwitch.update();
moveWheel(-1, 600);
}
moveWheel(-325, 800); // Go to next position
delay(2000);
...
void moveWheel(int wSteps, int wDelay) {
if(wSteps >0) {
digitalWrite(directionPin, LOW);
wheelPos++;
}
else {
digitalWrite(directionPin, HIGH);
wheelPos--;
}
for(int i = 0; i < abs(wSteps); i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(wDelay);
digitalWrite(stepPin, LOW);
delayMicroseconds(wDelay);
}
}
Thanks. I will check them out tomorrow.
But in my head it shouldn't matter how fast my loop is running. The delay() is between two calls to the moveWheel() function. The stepper (or any other part of the code) isn't supposed to do anything there.
The wheel moves as expected during the calls to the moveWheel().
This is the actual output I get:
-wheel runs until it finds starting position (while loop)
-wheel pauses for 2 seconds
-wheel runs 325 steps
I can't figure it out from the fragment provided. I put your code in a sketch and it works fine for me:
const byte HomeSwitchPin = 2;
const byte directionPin = 3;
const byte stepPin = 4;
void setup()
{
Serial.begin(115200);
delay(200);
pinMode(HomeSwitchPin, INPUT_PULLUP);
pinMode(directionPin, OUTPUT);
pinMode(stepPin, OUTPUT);
}
void moveWheel(int wSteps, int wDelay)
{
if (wSteps > 0)
{
digitalWrite(directionPin, LOW);
// wheelPos++;
}
else
{
digitalWrite(directionPin, HIGH);
// wheelPos--;
}
for (int i = 0; i < abs(wSteps); i++)
{
digitalWrite(stepPin, HIGH);
delayMicroseconds(wDelay);
digitalWrite(stepPin, LOW);
delayMicroseconds(wDelay);
}
}
void loop()
{
Serial.println("Homing");
while (digitalRead(HomeSwitchPin) == HIGH)
moveWheel(-1, 600);
Serial.println("Homed. Moving -325 steps");
moveWheel(-325, 800); // Go to next position
Serial.println("Move complete.");
delay(2000);
Serial.println("Delay complete.");
}
The output shows that after I short Pin 2 to Ground to signal that the Home switch has closed, it take about 1/2 second to go through the 325 steps and two seconds for the delay: