// Define pins for rotary encoder
#define CLK_PIN 2 // CLK pin of rotary encoder
#define DT_PIN 3 // DT pin of rotary encoder
#define LED_PIN 5 // LED pin
// Variables to store encoder state and count
volatile int encoderCount = 0;
volatile int prevCLKState = LOW;
void setup() {
Serial.begin(9600);
// Set LED pin as output
pinMode(LED_PIN, OUTPUT);
// Set CLK and DT pins as input with pullup resistors enabled
pinMode(CLK_PIN, INPUT_PULLUP);
pinMode(DT_PIN, INPUT_PULLUP);
// Attach interrupt for CLK pin
attachInterrupt(digitalPinToInterrupt(CLK_PIN), updateEncoder, CHANGE);
}
void loop() {
// Map encoder count to a range of brightness (0 to 255)
int brightness = map(encoderCount, 0, 60, 0, 255);
// Update LED brightness
analogWrite(LED_PIN, brightness);
// Print current brightness value
Serial.print("Brightness: ");
Serial.println(brightness);
delay(100); // Add a small delay for stability
}
// Interrupt service routine to update encoder count
void updateEncoder() {
int CLKState = digitalRead(CLK_PIN);
int DTState = digitalRead(DT_PIN);
// Check if the CLK state has changed
if (CLKState != prevCLKState) {
// Check the direction of rotation
if (CLKState == HIGH && DTState == LOW) {
encoderCount++; // Clockwise rotation
} else if (CLKState == LOW && DTState == HIGH) {
encoderCount--; // Counterclockwise rotation
}
}
// Update previous CLK state
prevCLKState = CLKState;
// Ensure encoder count stays within bounds
encoderCount = constrain(encoderCount, 0, 60);
}