// http://electronoobs.com/eng_arduino_tut125.php
// Rotary Encoder Inputs
#define Clock 9 //Clock pin connected to D9
#define Data 8 //Data pin connected to D8
#define Push 10 //Push button pin connected to D10
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 8 (Data) interrupt. Set pin D8 to trigger an interrupt on state change.
PCMSK0 |= (1 << PCINT1); //Pin 9 (Clock) interrupt. Set pin D9 to trigger an interrupt on state change.
// Setup Serial Monitor
Serial.begin(9600);
// 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 & B00000010); //Check pin D9 state? Clock
StateData = (PINB & B00000001); //Check pin D8 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
}
}
}