#include <Servo.h>
//define our pins
#define SERVO_PIN 9
#define SERVO_MAX 180
#define SERVO_MIN 0
Servo servo;
//inital position
int ServoPos = SERVO_MAX;
//desired psition
int DesiredPos = SERVO_MIN;
//timer vars
unsigned long lastStep = 0;
int servoSpeed = 10;
void setup() {
//attach servo to pin
servo.attach(SERVO_PIN);
//move to inital position
servo.write(ServoPos);
//set our new desired position..
DesiredPos = ServoPos - SERVO_MAX;//back to 0
}
void loop() {
//step to our new postion..
//step returns true desired pos reached..
if (ServoStep()) {
//switch pos..
if (DesiredPos == SERVO_MIN)
{
DesiredPos = SERVO_MAX;
}
else {
DesiredPos = SERVO_MIN;
}
}
}
//step servo 1 setp at a time till we reach
//our final position, returns true if done..
bool ServoStep() {
bool fin = false;
//timer check
if (millis() - lastStep >= servoSpeed) {
lastStep = millis();
//if we're not there yet..
if (ServoPos != DesiredPos) {
servo.write(ServoPos);//step
if (DesiredPos < ServoPos)
ServoPos--;//subtract 1
else
ServoPos++;
} else {
fin = true;
}
}
return fin;
}