Hello, I'm trying to get a stepper motor with a driver to move back and forth a certain distance ten times when a push button is pressed. After the ten back and forth movements, I need it to stop. I've had experience using Java and I'm familiar with for and while loops but I just can't seem to get a counter to work. Every time I try to incorporate a counter or delay function into the code, the motor just stops moving. I'm also having a lot of trouble with the push button as it does not work the same way as the simple LED code examples on this forum.
Here is the code that works without the push button or for loop: it just goes back and forth repeatedly.
#include <AccelStepper.h>
int Stepper1Pulse = 5; // Pulse or step pin
int Stepper1Direction = 6; // Direction pin
int speedpot = A0; // Potentiometer
int startSwitch = 2; //StartSwitch Pin
int val = 0; //pushswitch initial value
int val2 = 0;
int Motor1speed = 0;
int speedmin = 0; //pulses per second
int speedmax = 4000; //pulses per second
int distance = 20;
AccelStepper step1(1, Stepper1Pulse, Stepper1Direction);
void setup()
{
// Change these to suit your stepper if you want
step1.setMaxSpeed(1000);
step1.setAcceleration(200);
//step1.moveTo(distance);
}
void loop()
{
step1.moveTo(100);
step1.run();
step1.moveTo(-100);
step1.run();
}
Here is my code that I thought would work but doesn't:
#include <AccelStepper.h>
int Stepper1Pulse = 5; // Pulse or step pin
int Stepper1Direction = 6; // Direction pin
int speedpot = A0; // Potentiometer
bool fHasLooped = false;
int startSwitch = 2; //StartSwitch Pin
int val = 0; //pushswitch initial value
int val2 = 0;
int Motor1speed = 0;
int speedmin = 0; //pulses per second
int speedmax = 100; //pulses per second
AccelStepper step1(1, Stepper1Pulse, Stepper1Direction);
void setup() {
// put your setup code here, to run once:
step1.setMaxSpeed (speedmax);
//step1.setSpeed(0);
step1.setAcceleration(90);
pinMode(Stepper1Pulse, OUTPUT);
pinMode(Stepper1Direction, OUTPUT);
digitalWrite(Stepper1Pulse, LOW);
digitalWrite(Stepper1Direction, LOW);
step1.moveTo(180);
step1.run();
delay(1000);
step1.moveTo(0);
}
void loop() {
// put your main code here, to run repeatedly:
val = digitalRead(startSwitch); // read input value
if (val == HIGH || val2 > 0) {
val2 = 1;
if ( fHasLooped == false)
{
for (int x = 0; x < 10; x++)
{
step1.moveTo(100);
step1.run();
step1.moveTo(-100);
step1.run();
}
}
fHasLooped = true;
}
}
Thanks so much for the help. Sorry if I formatted something incorrectly, I am brand new to arduino and have no experience with this language at all. I understand the concepts of what I have to do but I don't really know the syntax of this language or how to interface the arduino with the counter. Really appreciate everyone's help!