I'm trying to run a stepper motor for three runs and then stop so that the fixture it's running can be reset. I've built the code to run the motor, and it runs properly, but it won't stop (it just runs until I unplug it basically). How can I make it stop after the three runs? I've tried if statements, for loops, when statements, etc. but nothing is working. Below is the code I currently have:
If you really only want the code to run once (i.e. 3 iterations of the motor) then put all the code in setup() and leave loop() empty.
The more realistic solution is to have a variable that counts how many time the code runs and have it stop calling the stepper code when the count reaches 3.
There is no need to have 3 repeats of the same code in loop(). The whole purpose of loop() is to make it easy to repeat things.
Hi Robin2- thanks for responding!
I tried doing that with a for loop, but it wouldn't run the motor at all when I upload that code. Do you have any suggestions for that?
Everything was the same as above, but I used this in the loop:
void loop ()
{
for (int c = 0; c > 3; ++c) {
stepper.runToNewPosition(0);
stepper.runToNewPosition(10000);
delay(100);
stepper.runToNewPosition(10000);
stepper.runToNewPosition(0);
delay(1000);
}
}
Should I have something before the for loop to initialize the motor? I'm used to a different programming setup and I know what I want it to do, just can't seem to get the follow-through. Thanks so much for helping!
AH! I see. Thank you, that makes so much sense. I was seeing it as once the condition is true, the loop stops. I've changed it to run in decrement, and now it's working. For some reason, now it won't stop running, though. Is that just a condition of the loop or should it be stopping? Here is the code I have written.
Thanks so much for your help!
#define stepPin A4 //GPIO hooked to step
#define dirPin A5 // GPIO hooked up to dir
#define enPin A3 // GPIO hooked to enable
#include <AccelStepper.h>
// Define a stepper and the pins it will use
AccelStepper stepper(1,stepPin,dirPin); // Defines a separate stepper driver and step/dir pins
void setup()
{
stepper.setEnablePin(enPin);
stepper.setMaxSpeed(1100.0);
stepper.setAcceleration(1200.0);
digitalWrite(enPin,LOW);
}
void loop ()
{
for (int c = 3; c > 0; c = --c) {
stepper.runToNewPosition(0);
stepper.runToNewPosition(10000);
delay(100);
stepper.runToNewPosition(10000);
stepper.runToNewPosition(0);
delay(1000);
}
}