Optical encoder with interrupt

Hello everyone,

I'm trying to read the singals from an optical encoder with my mega 2560. The optical encoder has 4 pins: GND, 5V+, ChA, ChB. (http://fabacademy.org/archives/2014/students/moreira.guilherme/site_en/Agilent_Optical_Encoders.pdf)

I connect the wires of ChA and ChB to one of the interrupt pins of the mega 2560.

I'm using a round disk with 1800 lines. With this code I get a message for every degree the disk is turned. This is working fine.

But it only work with the pins 18, 19, 20 and 21. The other interrupt pins A2 and A3 aren't working. They also used to work before like the other pins. Is it possible to only damage the interrupt function?

All the other funtions (that I know) of these pins are working: HIGH: Checked with the voltmeter and GND. I've measured 5V. LOW: 0V Input and output are working.

Here is the code. Maybe i did something wrong. For selecting other pins, I switch A2 and A3 with 18,19,20 or 21.

#define encoderPinA A2
#define encoderPinB A3

volatile  int encoderPos = 0;
volatile  int angle = 0;
 int lastReportedPos = 1;

boolean A_set = false;
boolean B_set = false;


void setup() {

  pinMode(encoderPinA, INPUT); 
  pinMode(encoderPinB, INPUT); 




// encoder pin on interrupt 0 (pin 2)
  attachInterrupt(digitalPinToInterrupt(encoderPinA), doEncoderA, CHANGE);
// encoder pin on interrupt 1 (pin 3)
  attachInterrupt(digitalPinToInterrupt(encoderPinB), doEncoderB, CHANGE);

  Serial.begin(9600);
}


void loop(){ 
  if (lastReportedPos != angle) {
    Serial.print("Index:");
    Serial.print(angle, DEC);
    Serial.println();
    lastReportedPos = angle;
  }}



// Interrupt on A changing state
void doEncoderA(){
  // Test transition
  A_set = digitalRead(encoderPinA) == HIGH;
  // and adjust counter + if A leads B
  encoderPos += (A_set != B_set) ? +1 : -1;
if (0==encoderPos-20){
encoderPos=0;
angle++;}
if (0==encoderPos+20){
encoderPos=0;
angle--;}

}

// Interrupt on B changing state
void doEncoderB(){
  // Test transition
  B_set = digitalRead(encoderPinB) == HIGH;
  // and adjust counter + if B follows A
  encoderPos += (A_set == B_set) ? +1 : -1;
if (0==encoderPos-20){
encoderPos=0;
angle++;}
if (0==encoderPos+20){
encoderPos=0;
angle--;}
}

Maybe someone has an idea. Thank you.

The other interrupt pins A2 and A3 aren't working.

Those pins cannot be used for normal interrupts on a Mega

See attachInterrupt()

Ok Thank you. I read this page maybe 3 times today, but I didn’t see my mistake.

I was pretty sure, that I used A2 and A3 for the first test. Maybe I should check my memory.

It’s also working, if I use pin 2 and 3.