I am making a CD like a tray that open and close. I am using a stepper motor, L289 motor drive. and here is my code. When I press the push button, the motor takes only one revolution. Please suggest changes, I want to make it in such a way that it stops when I hit the limit switch.
#include <Bounce2.h>
#include <Stepper.h>
const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
const byte limitSwitchLeftPin = 6;
const byte limitSwitchRightPin = 7;
const byte triggerPin = 5;
Bounce limitSwitchLeft = Bounce();
Bounce limitSwitchRight = Bounce();
Bounce triggerButton = Bounce(); //trigger for motor
void setup() {
// put your setup code here, to run once
myStepper.setSpeed(60);
limitSwitchLeft.attach(limitSwitchLeftPin, INPUT_PULLUP);
limitSwitchLeft.interval(25);
limitSwitchRight.attach(limitSwitchRightPin, INPUT_PULLUP);
limitSwitchRight.interval(25);
triggerButton.attach(triggerPin, INPUT_PULLUP);
triggerButton.interval(25);
Serial.begin(9600);
//assuming motor is already one one junction
Serial.println("Incubator starting. motor is now at rest");
delay(2000);
}
enum states { STATE_IDLE, STATE_MOVING_RIGHT, STATE_MOVING_LEFT };
int currentState = STATE_IDLE;
void loop() {
// put your main code here, to run repeatedly:
limitSwitchLeft.update();
limitSwitchRight.update();
triggerButton.update();
bool limitSwitchLeftState = limitSwitchLeft.read(); //switch are input pullup. high state is zero
bool limitSwitchRightState = limitSwitchRight.read();
switch (currentState) {
case STATE_IDLE:
// motor is off, waiting for trigger button to be pressed
if (triggerButton.fell())
{
Serial.println("button to trigger start motor has been presssed");
// figure out which way to move
if (limitSwitchLeftState == HIGH && limitSwitchRightState == LOW)
{
Serial.println("Moving right now");
myStepper.step(-stepsPerRevolution);
currentState = STATE_MOVING_RIGHT;
}
else if (limitSwitchLeftState == LOW && limitSwitchRightState == HIGH)
{
Serial.println("Moving left now");
myStepper.step(stepsPerRevolution);
currentState = STATE_MOVING_LEFT;
}
else if (limitSwitchLeftState == HIGH && limitSwitchRightState == HIGH)
{
// neither limit switch is tripped, arbitrarily move left
Serial.println("No limit switches detected, moving left now");
myStepper.step(stepsPerRevolution);
currentState = STATE_MOVING_LEFT;
}
else
{
Serial.println("Both limit switches detected, program halted");
myStepper.step(0);
while (1); // loop forever
}
}
break;
case STATE_MOVING_RIGHT:
// moving right so only check right limit switch
if (limitSwitchRightState == LOW)
{
Serial.println("Motor reached right. motor stopping");
myStepper.step(0);
currentState = STATE_IDLE;
}
break;
case STATE_MOVING_LEFT:
// moving left so only check left limit switch
if (limitSwitchLeftState == LOW)
{
Serial.println("Motor has reached left. Motor stopping");
myStepper.step(stepsPerRevolution);;
currentState = STATE_IDLE;
}
break;
}
}