/*
Variant of led brightness that uses the switch (ezButton) to
turn on and off the led but still keeping the brightness level.
Brightness value can still be changed while light is off.
* Created by ArduinoGetStarted.com
*
* This example code is in the public domain
*
* Tutorial page: https://arduinogetstarted.com/tutorials/arduino-rotary-encoder-led
*/
#include <ezButton.h>
#define CLK_PIN 2
#define DT_PIN 3
#define SW_PIN 4
#define LED_PIN 9
#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; // initial middle value
bool ledToggle = false; //Light switch
ezButton button(SW_PIN); //create ezButton object
void setup() {
Serial.begin(9600);
// configure encoder pins as inputs
pinMode(CLK_PIN, INPUT);
pinMode(DT_PIN, INPUT);
button.setDebounceTime(50);
ledToggle = true;
// read the initial state of the rotary encoder's CLK pin
prev_CLK_state = digitalRead(CLK_PIN);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
button.loop(); //MUST call the loop() function first
// 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;
Serial.print("COUNTER: ");
Serial.print(counter);
Serial.print(" | BRIGHTNESS: ");
Serial.println(brightness);
}
if (button.isPressed()) {
ledToggle =! ledToggle;
//Serial.print(ledToggle);
//Serial.print(brightness);
}
// if switch is on display the brightness of LED according to the counter
if (ledToggle) {
analogWrite(LED_PIN, brightness);
} else {
analogWrite(LED_PIN, 0);
}
// save last CLK state
prev_CLK_state = CLK_state;
}