I want the servo to rotate for 5 seconds, then wait for 10 seconds. During this waiting period I want the servo to be able to take input from the two pushbuttons that rotate the servo in either direction.
This is the program I have so far:
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
unsigned long currentMillis = 0; // stores the value of millis()
unsigned long runtime = 5000; // stores time for the servo to run
unsigned long waittime = 10000; // stores time for the servo to wait
void setup() {
// put your setup code here, to run once:
pinMode (2, INPUT); // pushbutton input 1
pinMode (3, INPUT); // pushbutton input 2
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
unsigned long currentMillis = millis(); // grab current time
if ((unsigned long)currentMillis <= runtime) { // rotates the servo till currentMillis is < 5000ms
for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(1); // waits 1ms for the servo to reach the position
}
for(pos = 180; pos>=0; pos-=1) // goes from 180 degrees to 0 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(1); // waits 1ms for the servo to reach the position
}
}
if ((unsigned long)currentMillis <=waittime+runtime) {
myservo.write(0); // sends the servo back to 0 degrees
if (digitalRead(2) == HIGH && pos < 180) { // checking if pushbutton is pressed and servo position is less than 180
pos++; // increment position
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(1); // waits 1ms for the servo to reach the position
}
if (digitalRead(3) == HIGH && pos > 0) { // checking if pushbutton is pressed and servo position is more than 0
pos--; // decrement position
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(1); // waits 1ms for the servo to reach the position
}
}
runtime = currentMillis + 5000; // adding 5000ms to 'runtime' variable for the next loop
}
When I upload this sketch, rather than rotating for 5 seconds (in accordance with first 'if' condition) and the returning to 0 degrees and waiting for pushbutton input (in accordance with the second 'if' condition), the servo just keeps on indefinitely rotating in clockwise and anticlockwise direction. Also, pressing the pushbuttons doesn't seem to affect the continuous clockwise and anti-clockwise rotation. Is the program getting stuck in the first 'if' condition?
Can someone please point out the corrections I need to make? If there is anything else you would like to know that would help you solve this issue better then I'll update the post.
Servo is connected to digital pin 9. Positive pin of the servo is connected to +5v on arduino, negative pin to GND on arduino. This is how the pushbuttons are connected:
