I have a stepper motor moving an arm anticlockwise until it interupts a light beam, a counter records the number of steps: It then moves clockwise the same number of steps and then waits for a button to be pressed. It works, repeatedly moving between the two positions, except that the Serial.println statement only returns one message "No of steps = 0" however many times I run the cycle. I cannot see the mistake in the program, and hope one of you can. Thank you in anticipation.
// define pins
#define stepPin 3
#define dirPin 2
#define testPin 8
long flipStep = 0; //Stepper motor step counter
void setup() {
Serial.begin(9600);
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(testPin, INPUT_PULLUP); //Button connects to GND when pushed
}
void loop() {
digitalWrite(dirPin, LOW); //Anticlockwise
while (analogRead(A1) > 250) { //Light on sensor
step(2000); //Call to single step at speed dictated by pulse duration
flipStep++;
}
Serial.print("No of steps = ");
Serial.println(flipStep);
digitalWrite(dirPin, HIGH); //Clockwise
while (flipStep > 0) {
step(2000);
flipStep--;
}
while (digitalRead(testPin) == HIGH) { //When button is pressed, program moves on
//Do nothing
}
}
void step(int speed) {
digitalWrite(stepPin,HIGH);
delayMicroseconds(speed);
digitalWrite(stepPin,LOW);
delayMicroseconds(speed);
}