I have a sketch that calls for dc motors to run one way, then delay, then run another way, then call the servo to spin. The problem Im having is that the servo is spinning constantly from the beginning of the sketch non stop. It does seem to change directions when the pos variable is logged, which is when the servo is supposed to run and it does seem to run in the correct directions during that time. But then it just keeps going "straight" until the runServo method is called again.
Is it because its a 360 degree servo or because I have to stop the servo explicitly?
#include <Servo.h>
#include <AFMotor.h>
AF_DCMotor motor1(1);
AF_DCMotor motor2(4);
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
// Start up serial connection
Serial.begin(9600); // baud rate
Serial.flush();
}
void runServo(){
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
Serial.println(pos);
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
Serial.println(pos);
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
void loop(){
delay(2000);
// SPIN AROUND
motor1.setSpeed(200);
motor1.run(FORWARD);
motor2.setSpeed(200);
motor2.run(FORWARD);
//STOP FOR A WHILE
delay(5000);
motor1.run(RELEASE);
motor2.run(RELEASE);
//RUN FORWARD
motor1.setSpeed(200);
motor2.setSpeed(200);
motor1.run(FORWARD);
motor2.run(BACKWARD);
//STOP FOR A WHILE
delay(5000);
motor1.run(RELEASE);
motor2.run(RELEASE);
runServo();
}