I have working code that moves a stepper motor a given distance after a button is pressed (using the AccelStepper library). However, I need to make it so that my sketch/function will move the stepper motor a given distance, then pause for x milliseconds, then call/execute the function again. This way the motor will move, pause, and repeat infinitely until it is stopped.
I'm a little confused about how to go about this. I suspect it's a simple implementation of a for loop. The full original code that only moves the motor forward once is below, but here is a snippet with my idea for making the code do what I want.
void loop() {
buttonsOne(); // when pressed moves stepper reverse
buttonsTwo(); // when pressed moves stepper forward
}
void buttonsTwo()
{
if (digitalRead(LEFT_ONE_PIN) == 0)
for (int i = 0; i <= 1000; i++)
{
stepper1.move(200);
// I'll add code here to that will trigger my camera/Optocoupler
delay(2000);
}
stepper1.run();
}
A few notes/questions:
I know that void buttonsTwo() is continuously looping. It's hard for me to understand, then, how the Arduino keeps track of actions that occur over time, like my motor moving a certain distance. But, I assume it keeps track of what's going on.
The for loop seems like a good solution because it will loop/repeat. But maybe this is no different than the void buttonsTwo() looping already? Though, I think void buttonsTwo() will stop looping once the button is no longer pressed.
I suspect I could also simply just have a function inside of void buttonsTwo() that simply calls itself?
Lastly, void buttonsTwo() is only executed when (digitalRead(LEFT_ONE_PIN) == 0). Do I need the function that repeatedly moves the motor to be outside of the void buttonsTwo() function so that the motor will keep moving even after the button is no longer pressed?
Full Original Code
#include <AccelStepper.h>
AccelStepper stepper1(AccelStepper::DRIVER, 9, 8);
bool flag = false;
#define LEFT_PIN 4
#define STOP_PIN 3
#define RIGHT_PIN 2
#define LEFT_ONE_PIN 5
#define RIGHT_ONE_PIN 6
void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin as output for Optocoupler
// digitalWrite(ledPin, LOW);
#define SPEED_PIN 0
#define MAX_SPEED 500
#define MIN_SPEED 0.01
stepper1.setMaxSpeed(10000.0);
pinMode(LEFT_PIN, INPUT_PULLUP);
pinMode(STOP_PIN, INPUT_PULLUP);
pinMode(RIGHT_PIN, INPUT_PULLUP);
pinMode(RIGHT_ONE_PIN, INPUT_PULLUP);
pinMode(LEFT_ONE_PIN, INPUT_PULLUP);
}
void loop() {
buttonsTwo();
}
void buttonsTwo() { // X number of steps forward and reverse
if (digitalRead(LEFT_ONE_PIN) == 0)
{
stepper1.setMaxSpeed(200.0);
stepper1.setAcceleration(500.0);
stepper1.move(200);
}
stepper1.run();
}
Thanks!