I want my tower pro 9g servo to start from pos=0, wait there for 1 second, then reach pos=90 wait for 1 second, then reach pos=180 and wait for 1 second. Now it goes back to pos=0 and repeats this cycle. I have written the following code for this purpose:
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(12); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos = 0; pos <= 180; pos += 90) { // goes from 0 degrees to 180 degrees
// in steps of 90 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(1000); // waits 1s for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 90) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(1000); // waits 1s for the servo to reach the position
}
}
But the behavior of the servo is not correct. It moves few degree from initial position and then comes back.
What is wrong with the logic in my code ?
for
loop ... the first loop already does what you want