/*
External Interrupt:
These interrupt are interpreted by hardware and are very fast.
which have the ability to detect RISING and FALLING pin change interrupts.
UNO , NANO has only 2 External Interrupt pins: 2,3
Mega has
2,3,18,19,20,21
Here need 3 interrupts so we need Mega
*/
// Define pins for rotary encoder
const int encoderPinA = 19; // CLK
const int encoderPinB = 20; // DT
const int buttonPin = 21; // Pin for push button (change as needed)
int counter = 0;
int currentStateCLK;
int lastStateCLK;
String currentDir ="";
volatile bool buttonPressed = false;
void setup() {
pinMode(encoderPinA, INPUT_PULLUP);
pinMode(encoderPinB, INPUT_PULLUP);
pinMode(buttonPin, INPUT_PULLUP);
// Read the initial state of CLK
lastStateCLK = digitalRead(encoderPinA);
// Attach interrupts
attachInterrupt(digitalPinToInterrupt(encoderPinA), updateEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(encoderPinB), updateEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(buttonPin), handleButtonPress, FALLING);
Serial.begin(9600);
}
void loop() {
if (buttonPressed) {
Serial.println("Button Pressed! Reset Counter");
buttonPressed = false; // Reset button state
counter =0;
}
delay(100); // Adjust as needed
}
void updateEncoder(){
// Read the current state of CLK
currentStateCLK = digitalRead(encoderPinA);
// If last and current state of CLK are different, then pulse occurred
// React to only 1 state change to avoid double count
if (currentStateCLK != lastStateCLK && currentStateCLK == 1){
// If the DT state is different than the CLK state then
// the encoder is rotating CW so decrement
if (digitalRead(encoderPinB) != currentStateCLK) {
counter ++;
currentDir ="CW";
} else {
// Encoder is rotating CCW so increment
counter --;
currentDir ="CCW";
}
Serial.print("Direction: ");
Serial.print(currentDir);
Serial.print(" | Counter: ");
Serial.println(counter);
}
// Remember last CLK state
lastStateCLK = currentStateCLK;
}
void handleButtonPress() {
// Handle button press
buttonPressed = true;
}