#include <Servo.h>
Servo servo1;
Servo servo2;
byte servo1pin = 5, servo2pin = 6;
int servo1home = 180, servo2home = 0;
int servoCount = 0, dir = 1, speedControl = 9;
int speedMax = 3, speedMin = 9; // delay
#define ENC_CK 2 // encoder
#define ENC_DT 3
#define ENC_SW 4 // button
void setup() {
Serial.begin(115200);
pinMode(ENC_CK, INPUT);
pinMode(ENC_DT, INPUT);
pinMode(ENC_SW, INPUT_PULLUP);
servo1.attach(servo1pin); // start the servos
servo2.attach(servo2pin);
servo1.write(servo1home);
servo2.write(servo2home);
attachInterrupt(digitalPinToInterrupt(ENC_CK), readEncoder, FALLING);
while (digitalRead(ENC_SW)); // wait for switch press
}
void loop() {
if (servoCount > 180 || servoCount < 0)
dir = -dir;
delay(speedControl);
servo1.write(servoCount);
servo2.write(180 - servoCount);
servoCount += dir;
}
void readEncoder() {
Serial.print(speedControl);
int dtValue = digitalRead(ENC_DT);
if (dtValue == HIGH) {
speedControl++;
}
if (dtValue == LOW) {
speedControl--;
}
if (speedControl > speedMin)
speedControl = speedMin;
if (speedControl < speedMax)
speedControl = speedMax;
}
(START)
CONTROL