Hi, I realize controlling one servo with a simple push button shouldn't be too difficult, but I really need the servo to only sweep the 90 degrees and then back and stop, until I press a push button again. I have been searching and re-coding for a few days now but I can't get the single sweep. What I do have is my servo sweeping at the angles I would like and the push button working (I have attached an LED to assure that). The push button works to turn the servo off and on if I time the moment I press it at the exact moment the servo completes a sweep and before it starts the next one. I read a forum question that addressed this issue similarly, however it didn't help. I would appreciate the help tremendously! Thank you and the code is posted below.
#include <Servo.h>
#define LED 13 // the pin for the LED
#define BUTTON 7 // the input pin where the pushbutton is connected
Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created
int pos = 0; // variable to store the servo position
int val = 0; // val will be used to store the state of the button
int old = 0; // variable stores the previous value of "val"
int state = 0; // 0 = LED state is off 1 = LED state is on
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop()
{val = digitalRead(BUTTON); // read input value and store it
// check whether the input is HIGH(button pressed)
if ((val == HIGH) && (old == LOW))
{ state = 1 - state;
delay(50);
}
old = val ;
if (state == 1) {
digitalWrite(LED,HIGH); // turn LED ON
for(pos = 0; pos < 90; pos += 1) // goes from 0 degrees to 90 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 = 90; pos>=1; pos-=1) // goes from 90 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(LED, LOW);
}
}