Hello, I've been working on a fairly simple program and am trying to use a button to control when a stepper motor starts moving and keeps moving until the button is pressed again. I have gotten the button to start the motor, but it will not stop the motor. Can someone have a look at my code and tell me what I might be doing wrong.
Thanks!
-Pat
int DIR_PIN = 3; //Pin 3 Dir
int STEP_PIN = 2; //Pin 2 Step
int MS1 = 13; // PIN 13 = MS
int MS2 = 9; // PIN 9 = MS2
int SLEEP = 12; // PIN 12 = SLP
int switchPin = 8; //define switch to pin 8
boolean lastButton = LOW; //part of debounce function
boolean currentButton = LOW; //part of debounce function
boolean motOn = LOW; //low puts driver into sleep mode, high turns it on
void setup() {
pinMode(DIR_PIN, OUTPUT); // set pin 3 to output
pinMode(STEP_PIN, OUTPUT); //set pin 2 to output
pinMode(MS1, OUTPUT); // set pin 13 to output
pinMode(MS2, OUTPUT); // set pin 9 to output
pinMode(switchPin, INPUT); // set pin 8 to input
pinMode(SLEEP, OUTPUT); // set pin 12 to output
}
boolean debounce(boolean last) //debounce function for switch
{
boolean current = digitalRead(switchPin);
if (last != current)
{
delay(5);
current = digitalRead(switchPin);
}
return current;
}
void loop()
{
currentButton = debounce(lastButton);
if (lastButton == LOW && currentButton == HIGH)
{
motOn = !motOn; //motOn is boolean variable for switch on/off
}
lastButton = currentButton;
digitalWrite(SLEEP, motOn); //set SLEEP pin to value of motOn variable
while (motOn == HIGH){ //may be always on ?
move();
}
}
void move()
{
digitalWrite(MS1,(1)); // Set state of MS1 to high -Pat
digitalWrite(MS2,(1)); // Set state of MS2 to high -Pat
//rotate a specific number of microsteps (8 microsteps per step)
//a 200 step stepper would take 1600 micro steps for one full revolution
rotate(-30, .5); //rotate 30 uSteps @ .5 speed
delay(2000); //wait 2 seconds before rotating again
// digitalWrite(SLEEP, motOn); //trying to get the button to turn the motor back off...this didn't work
//motOn = LOW; //testing manually setting the variable to low to see if the motor will stop...this worked to shut the motor down
}
void rotate(int steps, float speed){
//rotate a specific number of microsteps (8 microsteps per step) - (negitive for reverse movement)
//speed is any number from .01 -> 1 with 1 being fastest - Slower is stronger
int dir = (steps > 0)? HIGH:LOW;
steps = abs(steps);
digitalWrite(DIR_PIN,dir);
float usDelay = (1/speed) * 70;
for(int i=0; i < steps; i++){
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(usDelay);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(usDelay);
}
}