Hello
Try this sketch and check it out for your project.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
const int ServoPin = 9;
const int ButtonPin = 8;
void setup() {
pinMode(ButtonPin, INPUT_PULLUP);
myservo.attach(ServoPin); // attaches the servo on pin 9 to the servo object
}
void loop() {
static bool stateNew = false;
static bool turn = false;
static byte control_ = 0;
bool stateRecent = !digitalRead(ButtonPin);
if (stateNew != stateRecent) {
delay(20);
stateNew = stateRecent;
if (stateNew) control_++, turn = true;
}
if ((control_ & 1) && turn) {
for (int pos = 0; pos < 180; pos++) // 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
}
}
if (!(control_ & 1) && turn) {
for (int pos = 180; pos > 0; pos--) // 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(15); // waits 15ms for the servo to reach the position
}
}
turn = false;
}
Have a nice day and enjoy coding in C++.