rotary encoder pulses missing

Hi
I use the code for rotary encoder from you tube and I send in the attachment. The connection of the rotary encoder with the arduino is also in the attachment. When I have small speeds of the rotary encoder arduino is reading full resolution but when I turn the shaft of the rotary encoder little bit faster arduino is missing pulses. In the datasheet of rotary encoder is write speed 2000 rev/min.For capacitor in the connection I use 100 nF. What could be the problem?
Regards
Riste

ENCODER1.ino (834 Bytes)

download.png

Please use code tags to post code, so it looks like this:

int pulses, A_SIG =0 ,B_SIG=1;

void setup() {
attachInterrupt(0,A_RISE,RISING);
attachInterrupt(1,B_RISE,RISING);
Serial.begin(9600);

}

void loop() {
  

}
void A_RISE(){
  detachInterrupt(0);
  A_SIG=1;
  if(B_SIG==0)
  pulses++;
  if(B_SIG==1)
  pulses--;
  Serial.println(pulses);
  attachInterrupt(0,A_FALL,FALLING);
}

void A_FALL(){
  detachInterrupt(0);
  A_SIG=0;
  if(B_SIG==1)
  pulses++;
  if(B_SIG==0)
  pulses--;
  Serial.println(pulses);
  attachInterrupt(0,A_RISE,RISING);
}

void B_RISE(){
  detachInterrupt(1);
  B_SIG=1;
  if(A_SIG==1)
  pulses++;
  if(A_SIG==0)
  pulses--;
  Serial.println(pulses);
  attachInterrupt(1,B_FALL,FALLING);
}

void B_FALL(){
  detachInterrupt(1);
  B_SIG=0;
  if(A_SIG==0)
  pulses++;
  if(A_SIG==1)
  pulses--;
  Serial.println(pulses);
  attachInterrupt(1,B_RISE,RISING);
}

The problem is that Serial.println takes time, and is causing the program to miss pulses.

Remove the print statements.

Also, the constant use of detachInterrupt and attachInterrupt is very slow and inefficent.

Shuffling between RISING and FALLING interrupt triggers is not the way to do this. Use CHANGE, read the state of the interrupt pin in the ISR to see whether it is high (interrupt triggered by rise) or low(interrupt triggered by fall) and proceed with your routine based on what occurred.

See Nick Gammon's interrupt tutorial for tips on how to declare variables, access them safely and code an ISR.

For capacitor in the connection I use 100 nF

... but your circuit shows 10 nF. So the signal has 10x higher filtering. If the encoder's output can switch 5mA, then you could replace the pullup resistors with 1K, if you don't have the smaller capacitors available.

Note the time constant you now have for filtering is 1ms. The circuit shown would result in 0.1ms time constant.

Other reference:
http://playground.arduino.cc/Main/RotaryEncoders