Hey guys, i've been working on a bit of code to move a camera rail, and I have it functioning but when it comes to reversing the stepper motor im a bit stuck, it only reverses for a couple of seconds and then goes back into forward direction. Please read my code and help me out, also I want to add another momentary switch to stop and start the motor. Thanks,
#include <AFMotor.h>
// Connect a stepper motor with 360 steps per revolution
// to motor port #1 (M1 and M2)
AF_Stepper motor(180, 1);
const int PotPin = A5; // Change this if pot is connected to another pin
int direction = FORWARD; // Where we are going
int speed = 0; // How fast
int potVal = 1024; // Current potvalue
int buttonState = 0; // variable for reading the pushbutton status
const int buttonPin = 2; // the number of the pushbutton pin
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
}
void loop() {
potVal = analogRead(PotPin);
{
direction = FORWARD;
speed = map(potVal, 0, 1023, 50, 1); // Map value from pot-range to motorspeed-range }
buttonState = digitalRead(buttonPin); // read the state of the pushbutton value:
if (buttonState == HIGH)
{
direction = BACKWARD;
}
// print out the variables:
Serial.print("Read: ");
Serial.print(potVal);
Serial.print ("Button: ");
Serial.print (buttonState);
Serial.print(" direction: ");
if (direction==FORWARD)
Serial.print("Forward");
Serial.print(" Speed: ");
Serial.println(speed); // End of line, so also make it go a line
// make motor go a step
motor.setSpeed(speed); // Set speed of motor
motor.step(2,direction,MICROSTEP);
// You can change SINGLE to SINGLE, DOUBLE, INTERLEAVE or MICROSTEP
delay(1); // delay in between reads for stability
}}
Its a bit messy, it's been copied and pasted from other examples
EDIT: I would also like to know how I change the analogue pins a0-a5 to digital pins, do I just call them pins 14-19?
ANOTHER EDIT: when I have my stepper running in forward direction there is 0.6 v on the digital pin 2 and occasionaly the stepper will switch directions as if the signal is too "High" to be "Low" and the serial monitor shows the button state changing from high to low, do I need to use a pull down resistor?