/*
* Created by ArduinoGetStarted.com
*
* This example code is in the public domain
*
* Tutorial page: https://arduinogetstarted.com/tutorials/arduino-rotary-encoder-led
*/
#define CLK_PIN 2
#define DT_PIN 3
#define SW_PIN 4
#define LED_PIN 5
#define DIRECTION_CW 0 // clockwise direction
#define DIRECTION_CCW 1 // counter-clockwise direction
int counter = 0;
int direction = DIRECTION_CW;
int CLK_state;
int prev_CLK_state;
int brightness = 125; // middle value
void setup() {
Serial.begin(9600);
// configure encoder pins as inputs
pinMode(CLK_PIN, INPUT);
pinMode(DT_PIN, INPUT);
// read the initial state of the rotary encoder's CLK pin
prev_CLK_state = digitalRead(CLK_PIN);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// read the current state of the rotary encoder's CLK pin
CLK_state = digitalRead(CLK_PIN);
// If the state of CLK is changed, then pulse occurred
// React to only the rising edge (from LOW to HIGH) to avoid double count
if (CLK_state != prev_CLK_state && CLK_state == HIGH) {
// if the DT state is HIGH
// the encoder is rotating in counter-clockwise direction => decrease the counter
if (digitalRead(DT_PIN) == HIGH) {
direction = DIRECTION_CCW;
counter--;
brightness -= 10; // you can change this value
} else {
// the encoder is rotating in clockwise direction => increase the counter
direction = DIRECTION_CW;
counter++;
brightness += 10; // you can change this value
}
if (brightness < 0)
brightness = 0;
else if (brightness > 255)
brightness = 255;
// sets the brightness of LED according to the counter
analogWrite(LED_PIN, brightness);
Serial.print("COUNTER: ");
Serial.print(counter);
Serial.print(" | BRIGHTNESS: ");
Serial.println(brightness);
}
// save last CLK state
prev_CLK_state = CLK_state;
}