const int clkPin = 2; // Pin connected to CLK on the rotary encoder
const int dtPin = 3; // Pin connected to DT on the rotary encoder
const int swPin = 4; // Pin connected to SW on the rotary encoder
const int ledPins[] = {5, 6, 7, 8, 9, 10, 11, 12, 13, A0}; // Pins connected to the LEDs
int ledCount = 10;
int level = 0;
int lastStateCLK;
int currentStateCLK;
int lastButtonState;
void setup() {
// Initialize LED pins as output
for (int i = 0; i < ledCount; i++) {
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins[i], LOW); // Turn off all LEDs initially
}
// 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);
lastButtonState = digitalRead(swPin);
}
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
level++;
if (level > ledCount) level = ledCount;
} else {
// Turning counterclockwise
level--;
if (level < 0) level = 0;
}
// Update the LED bar graph
for (int i = 0; i < ledCount; i++) {
if (i < level) {
digitalWrite(ledPins[i], HIGH);
} else {
digitalWrite(ledPins[i], LOW);
}
}
}
// Read the button state
int currentButtonState = digitalRead(swPin);
// If the button is pressed, reset the LED bar graph
if (currentButtonState == LOW && lastButtonState == HIGH) {
delay(50); // Debounce delay
level = 0;
for (int i = 0; i < ledCount; i++) {
digitalWrite(ledPins[i], LOW);
}
}
// Update the last states
lastStateCLK = currentStateCLK;
lastButtonState = currentButtonState;
}
(really messy and bad wiring diagram XD)
Decrease ->
Increase ->