#include <Servo.h>
Servo myservo; // create servo object to control a servo
int encoderPinCLK = 2; // connect KY-040 CLK to digital pin 2
int encoderPinDT = 3; // connect KY-040 DT to digital pin 3
int encoderSwitch = 4; // connect KY-040 SW to digital pin 4
int val; // variable to read the encoder state
int encoderPos = 512; // variable to store the encoder position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(encoderPinCLK, INPUT);
pinMode(encoderPinDT, INPUT);
pinMode(encoderSwitch, INPUT_PULLUP); // Internal pull-up resistor for the switch
attachInterrupt(digitalPinToInterrupt(encoderPinCLK), updateEncoder, CHANGE);
}
void loop() {
// Use the encoder position directly or scale it as needed
val = map(encoderPos, 0, 1023, 0, 180);
myservo.write(val);
delay(15);
// Check the switch state
if (digitalRead(encoderSwitch) == LOW) {
// Reset to center position
encoderPos = 512;
}
}
void updateEncoder() {
int CLKstate = digitalRead(encoderPinCLK);
int DTstate = digitalRead(encoderPinDT);
if (CLKstate != DTstate) {
encoderPos++;
} else {
encoderPos--;
}
}