The Arduino code reading the photo interrupter and stepping the motor:
/*
Reads pulses on digital pin 2 Interrupt (0)
and sweeps the motor left to right one step at a time.
Comments and complaints https://www.nicknorton.net
*/
#include <Stepper.h>
int stepCount = 0; // steps the motor has taken
int maxSteps = 70; // steps to take before reversing direction
int turnsCounter = 0; // Miscount and it'll be a nightmare
int stepsPerRevolution = 48; // steps per motor revolution
// initialize the stepper library on pins 8 through 11 for a unipolar motor.
Stepper motor(stepsPerRevolution, 8,9,10,11);
void setup() {
Serial.begin(9600);
attachInterrupt(0, pulseright, FALLING); // photo interrupter on interrupt(0)
}
void loop() {
}
void pulseright() {
detachInterrupt(0); // Stop the interrupt routine from being interrupted.
turnsCounter++;
motor.step(1); // step one step clockwise
Serial.print("Right step: " );
Serial.print(stepCount);
Serial.print(" Turns: " );
Serial.println(turnsCounter);
stepCount++;
if (stepCount == maxSteps) {
pulseleft();
}
else
{
attachInterrupt(0, pulseright, FALLING);
}
}
void pulseleft() {
detachInterrupt(0); // Stop the interrupt routine from being interrupted.
turnsCounter++;
motor.step(-1); // step one step anticlockwise
Serial.print("Left step: " );
Serial.print(stepCount);
Serial.print(" Turns: " );
Serial.println(turnsCounter);
stepCount--;
if (stepCount == 0) {
pulseright();
}
else
{
attachInterrupt(0, pulseleft, FALLING);
}
}