i am putting a code for Quadrature Optical Encoders
i Just modified the existing code which used 1 interrupt and offered 2x resolution its just using two interrupts to increase the resolution to 4x i.e if encoder wheel had 30 counts/ rev it will give 120.
#define XaxisENCPinA 2 // X-AXIS encoder 1 on pins 2 and 4
#define XaxisENCPinB 3
double XaxisPos;
volatile double XaxisENCPos = 0;
void setup() {
Serial.begin(115200);
Serial.println("Linear Encoder Test 05-12-2014");
pinMode(XaxisENCPinA,INPUT);
pinMode(XaxisENCPinB,INPUT);
attachInterrupt(0, doXaxisENCA, CHANGE); // encoder pin on interrupt 0 (pin 2)
attachInterrupt(1, doXaxisENCB, CHANGE); // encoder pin on interrupt 0 (pin 2)
}
void loop() {
uint8_t oldSREG = SREG;
XaxisPos = XaxisENCPos;
SREG = oldSREG; // Restore interrupt status register
}
void doXaxisENCA() { // ************** X- AXIS ****************
if (digitalRead(XaxisENCPinA)) { // test for a low-to-high interrupt on channel A,
if ( !digitalRead(XaxisENCPinB)) { // check channel B for which way encoder turned,
XaxisENCPos = ++XaxisENCPos; // CW rotation
}
else {
XaxisENCPos = --XaxisENCPos; // CCW rotation
}
}
else { // it was a high-to-low interrupt on channel A
if (digitalRead(XaxisENCPinB)) { // check channel B for which way encoder turned,
XaxisENCPos = ++XaxisENCPos; // CW rotation
}
else {
XaxisENCPos = --XaxisENCPos; // CCW rotation
}
}
Serial.println(XaxisENCPos);
} // End of interrupt code for encoder #1
void doXaxisENCB() { // ************** X- AXIS ****************
if (digitalRead(XaxisENCPinB)) { // test for a low-to-high interrupt on channel A,
if ( digitalRead(XaxisENCPinA)) { // check channel B for which way encoder turned,
XaxisENCPos = ++XaxisENCPos; // CW rotation
}
else {
XaxisENCPos = --XaxisENCPos; // CCW rotation
}
}
else { // it was a high-to-low interrupt on channel A
if (!digitalRead(XaxisENCPinA)) { // check channel B for which way encoder turned,
XaxisENCPos = ++XaxisENCPos; // CW rotation
}
else {
XaxisENCPos = --XaxisENCPos; // CCW rotation
}
}
Serial.println(XaxisENCPos);
} // End of interrupt code for encoder #1