// Rotary Encoder Inputs
#define Clock 2 //Clock pin connected to D5
#define Data 3 //Data pin connected to D4
#define Push 4 //Push button pin connected to D13
int counter = 0; //Use this variable to store "steps"
int previous_counter = 0; //Use this variable to store previous "steps" value
int currentStateClock; //Store the status of the clock pin (HIGH or LOW)
int StateData; //Store the status of the data pin (HIGH or LOW)
int lastStateClock; //Store the PREVIOUS status of the clock pin (HIGH or LOW)
String currentDir =""; //Use this to print text
unsigned long lastButtonPress = 0; //Use this to store if the push button was pressed or not
void setup() {
/* Set encoder pins as inputs with pullups. If you use the Encoder Module, you don't need
* pullups for Clock and Data, only for the push button.*/
pinMode(Clock,INPUT_PULLUP);
pinMode(Data,INPUT_PULLUP);
pinMode(Push, INPUT_PULLUP);
//Here we activate pin change interruptions on pin D8 and D9 with PCINT0 and PCINT1
PCICR |= (1 << PCIE0); //enable PCMSK0 scan
PCMSK0 |= (1 << PCINT0); //Pin 4 (Data) interrupt. Set pin D4 to trigger an interrupt on state change.
PCMSK0 |= (1 << PCINT1); //Pin 5 (Clock) interrupt. Set pin D5 to trigger an interrupt on state change.
// Setup Serial Monitor
Serial.begin(115200);
// Read the initial state of Clock pin (it could be HIGH or LOW)
lastStateClock = digitalRead(Clock);
}
void loop() {
if(counter != previous_counter)
{
Serial.print("Counter: ");
Serial.println(counter);
}
delay(1);
}
/*In this case, the counter will automatically change its value in the interruption.
So all we need to do is to print its value in the void loop*/
ISR(PCINT0_vect){
cli(); //We pause interrupts happening before we read pin values
currentStateClock = (PINB & B00100000); //Check pin D5 state? Clock
StateData = (PINB & B00000100); //Check pin D4 state? Data
if (currentStateClock != lastStateClock){
// If "clock" state is different "data" state, the encoder is rotating clockwise
if (StateData != currentStateClock){
counter ++; // We increment
lastStateClock = currentStateClock; // Updates the previous state of the clock with the current state
sei(); //restart interrupts
}
//Else, the encoder is rotating counter-clockwise
else {
counter --; // We decrement
lastStateClock = currentStateClock; // Updates previous state of the clock with the current state
sei(); //restart interrupts
}
}
}