#include <Servo.h> // Servo library
Servo servoObject; // Create servo object to control
int servoPin = 3; // PWM pin for servo
int servoPosition = 0; // starting servo position
unsigned long oldMillis = 0, interval = 10; // reading interval in milliseconds
int angle;
int direction = 1;
void setup() {
Serial.begin(115200);
servoObject.attach(servoPin); // control servo object from a PWM pin
}
void loop() {
moveServo();
}
void moveServo() {
if (millis() - oldMillis > interval) { // compare event duration/difference to interval
oldMillis = millis(); // store the new event start
angle += direction;
if (angle > 180) {
angle = 180;
direction = -direction;
}
if (angle < 0) {
angle = 0;
direction = -direction;
}
servoObject.write(angle);
}
}