I've been trying to figure this out for awhile and I can't seem to get it. I want my servo to return to zero if the button is released and not complete the sequence or if anytime during the sequence the button is released it will return to zero. Right now the program I have, when I press the button, the servo rises to 90 degrees at a variable rate, then continues on to 180 and rocks back and fourth. Once the button is released it goes back to zero. All is good, but I want it to go back to zero immediately if at any time the button is released. It always wants to complete at least one cycle. Does anyone know how to get this to work? Any help would be appreciated.
Here is the code:
#include <VarSpeedServo.h>
VarSpeedServo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
const int buttonPin = 12; //sets pin 2 as button
const int buttonPin2 = 13; //sets pin 3 as button
const int ledPin = 1; // sets pin 13 as LED for testing purposes
int buttonState = 0; //sets button 1 as off
int buttonState2 = 0; // sets button 2 as off
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode (buttonPin, INPUT); // sets button as input
pinMode (ledPin, OUTPUT); // sets led as output
myservo.write(0,255,true);
delay (10);
}
void loop()
{
buttonState = digitalRead(buttonPin);
buttonState2 = digitalRead(buttonPin2);
if (buttonState == HIGH)
{
digitalWrite(ledPin, HIGH);
myservo.write(90,10,true);
delay(50);
for(pos = 90; 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(15); // waits 15ms for the servo to reach the position
}
{
for(pos = 180; pos>=90; pos-=1) // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
else {
digitalWrite(ledPin, LOW);
delay(50);
myservo.write(0,10,true);
delay(50);
}
}