const int encoderA_pin = 2;
const int encoderB_pin = 3;
volatile int encoderPosition = 0;
void encoderA_ISR() {
// Determine direction by checking Channel B
Serial.print("channle a :");
Serial.print(digitalRead(encoderA_pin));
Serial.print(" channle b :");
Serial.println(digitalRead(encoderB_pin));
if (digitalRead(encoderA_pin) == digitalRead(encoderB_pin)) {
encoderPosition++; // Clockwise
} else {
encoderPosition--; // Counterclockwise
}
}
void setup() {
Serial.begin(9600);
pinMode(encoderA_pin, INPUT);
pinMode(encoderB_pin, INPUT);
attachInterrupt(digitalPinToInterrupt(encoderA_pin), encoderA_ISR, CHANGE);
attachInterrupt(digitalPinToInterrupt(encoderB_pin), encoderA_ISR, CHANGE);
}
void loop() {
Serial.print("Position: ");
Serial.println(encoderPosition);
delay(2000);
}
/*
#define outputA 6
#define outputB 7
int counter = 0;
int aState;
int aLastState;
void setup() {
pinMode (outputA,INPUT);
pinMode (outputB,INPUT);
Serial.begin (9600);
// Reads the initial state of the outputA
aLastState = digitalRead(outputA);
}
void loop() {
aState = digitalRead(outputA); // Reads the "current" state of the outputA
// If the previous and the current state of the outputA are different, that means a Pulse has occured
if (aState != aLastState){
// If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
if (digitalRead(outputB) != aState) {
counter ++;
} else {
counter --;
}
Serial.print("Position: ");
Serial.println(counter);
}
aLastState = aState; // Updates the previous state of the outputA with the current state
}
*/