// Rotary Encoder Inputs
#define CLK 4
#define DT 2
#define SW 3
#define DPR 50 // Debounce timer for press and release
#define LPR 3000 // Long press/release in milliseconds
// LED Outputs
int led1 = 8;
int led2 = 9;
int led3 = 10;
int led4 = 11;
unsigned char readBits = 0b111; // 8 bits
unsigned char rotationBits = 0b011; // 8 bits
unsigned char buttonBits = 0b111; // 8 bits
int counter = 0;
String currentDir = "";
unsigned long lastActionButton = 0;
void setup() {
// Set encoder pins as inputs
pinMode(CLK,INPUT);
pinMode(DT,INPUT);
pinMode(SW, INPUT_PULLUP);
// Set LED pins as Outputs
pinMode (led1,OUTPUT);
digitalWrite (led1, LOW);
pinMode (led2,OUTPUT);
digitalWrite(led2, LOW);
pinMode (led3,OUTPUT);
digitalWrite(led3, LOW);
pinMode (led4,OUTPUT);
digitalWrite(led4, LOW);
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
readBits = digitalRead(SW) << 2 | digitalRead(CLK) << 1 | digitalRead(DT);
if ((rotationBits & 0b11) != (readBits & 0b11)) {
rotationBits = rotationBits << 2 | readBits & 0b11;
// Bit Pairs Cyclic Sequence (CLK DT Pair Bits):
// 1. 2. 3. 4. 5.
// 11 | 01 | 00 | 10 | 11 for CCW
// 11 | 10 | 00 | 01 | 11 for CW
if (rotationBits == 0b01001011 || rotationBits == 0b10000111) {
if (rotationBits == 0b01001011) {
currentDir = "CCW";
counter--;
} else {
currentDir = "CW";
counter++;
}
Serial.print("Direction: ");
Serial.print(currentDir);
Serial.print(" | Counter: ");
Serial.println(counter);
}
}
if ((buttonBits & 0b001) != (readBits >> 2 & 0b001)) {
// Bit Pairs Press Release Cyclic Sequence (OFF ON Pair Bits):
// 1. 2. 3. 4. (long press/release)
// 000 | 001 | 011 | 111 for OFF
// 111 | 110 | 100 | 000 for ON
if ((buttonBits & 0b001) == 0b000) {
buttonBits = 0b001;
} else {
buttonBits = 0b110;
}
// Starts counting time since button physically operated
lastActionButton = millis();
// LONG Press/Release Actions
} else if (abs(millis() - lastActionButton) > (unsigned long)LPR) {
if (buttonBits == 0b011) {
buttonBits = 0b111;
Serial.println("LONG released!");
} else if (buttonBits == 0b100) {
buttonBits = 0b000;
Serial.println("LONG pressed!");
}
// SIMPLE Press/Release Actions
} else if (abs(millis() - lastActionButton) > (unsigned long)DPR) {
if (buttonBits == 0b001) {
buttonBits = 0b011;
Serial.println("Button released!");
} else if (buttonBits == 0b110) {
buttonBits = 0b100;
Serial.println("Button pressed!");
}
}
// Put in a slight delay to help debounce the reading
delay(1);
}