#include <Servo.h>
// Pin definitions for the rotary encoder
const int clkPin = 2;
const int dtPin = 3;
const int swPin = 4;
// Pin definition for the servo motor
const int servoPin = 9;
Servo myServo;
int angle = 90; // Initial angle for the servo (0 to 180)
int lastStateCLK;
int currentStateCLK;
void setup() {
// Initialize the servo
myServo.attach(servoPin);
myServo.write(angle);
// Initialize rotary encoder pins
pinMode(clkPin, INPUT);
pinMode(dtPin, INPUT);
pinMode(swPin, INPUT_PULLUP);
// Read the initial state of the CLK pin
lastStateCLK = digitalRead(clkPin);
Serial.begin(9600); // For debugging purposes
}
void loop() {
// Read the current state of the CLK pin
currentStateCLK = digitalRead(clkPin);
// If the state has changed, then the encoder has been rotated
if (currentStateCLK != lastStateCLK) {
// Read the DT pin
int dtState = digitalRead(dtPin);
// Determine the direction of rotation
if (dtState != currentStateCLK) {
// Turning clockwise, increase angle
angle += 5;
if (angle > 180) angle = 180;
} else {
// Turning counterclockwise, decrease angle
angle -= 5;
if (angle < 0) angle = 0;
}
// Update the servo position
myServo.write(angle);
Serial.print("Angle: ");
Serial.println(angle);
}
// Update the last state
lastStateCLK = currentStateCLK;
// Read the button state (optional, for future use)
int buttonState = digitalRead(swPin);
}