I am trying to program my Arduino to run a stepper through a routine X number of times. Direction and speed is working fine but I am not familiar with using "For" statements to stop the motor after the necessary loops. I have looked at examples but am still lost. Would you please advise where the counter should be here? Thanks.
/*
Stepper Motor Controller
language: Wiring/Arduino
This program drives a unipolar or bipolar stepper motor.
The motor is attached to digital pins 8 and 9 of the Arduino.
The motor moves 100 steps in one direction, then 100 in the other.
Created 11 Mar. 2007
Modified 7 Apr. 2007
by Tom Igoe
*/
// define the pins that the motor is attached to. You can use
// any digital I/O pins.
#include <Stepper.h>
#define motorSteps 211 // change this depending on the number of steps
// per revolution of your motor
#define motorPin1 8
#define motorPin2 9
#define ledPin 13
// initialize of the Stepper library:
Stepper myStepper(motorSteps, motorPin1,motorPin2);
void setup() {
// set the motor speed at 60 RPMS:
myStepper.setSpeed(60);
// Initialize the Serial port:
Serial.begin(9600);
// set up the LED pin:
pinMode(ledPin, OUTPUT);
// blink the LED:
blink(3);
}
void loop() {
// Step forward 100 steps:
Serial.println("Forward");
myStepper.step(100);
delay(500);
// Step backward 100 steps:
Serial.println("Backward");
myStepper.step(-5'00);
delay(500);
}
// Blink the reset LED:
void blink(int howManyTimes) {
int i;
for (i=0; i< howManyTimes; i++) {
digitalWrite(ledPin, HIGH);
delay(200);
digitalWrite(ledPin, LOW);
delay(200);
}
}
I would like to stop the stepper after running back and forth a specific number of times. The code was copy/pasted without complete understanding, particularly the "for" statement. Do I need to write a "void stop" function? Sorry, I am less than a newbie at this. Could you advise a book/s that might help?
In Arduino sketches, the main() is already written and hidden from you. Instead, you provide a setup() function that will be called once, and a loop() function that will be called repeatedly forever.
You can do your counter the way you propose, if you change main() to loop() instead, but only because loop() is called repeatedly. The for() statement makes it self-contained so you can use the technique in any location.
Every loop in any programming language has three parts: an initialization, a bit of work inside the loop that may allow the condition to change, and a test of the condition to see if it's time to quit the loop.