Hey all!
I am using an optical encoder and interrupts on a Nano, and I seem to be able to get the right pulses when I rotate the encoder shaft slowly, but when I go fast it jumps and gives me smaller numbers of pulses counted. I have no idea why.
The optical encoder used has PPR of 5120, and max RPM of 5000, its an NPN (Open Circuit), and does ABZ (but I am only using AB at the moment, not sure how to use Z to be honest).
My questions are:
1- In my current code I am interrupting for rising of the A signal, what would happen if I measured the B Rising signal as well? What about if I also did the A & B Falling signal? I know that its supposed to increase my resolution, is that a good idea? How would I even implement it via code?
2- This is how I am calculating the potential max pulses the interrupt might need to log at max speed.
5000 RPM/60 seconds = ~83 Rounds per Second (RPS)
5120 PPR * 83 RPS = ~424000 pulses in a second at max RPM
therefore 1/42400 = ~0.000002seconds = 2microseconds
Is this calculation correct?
3- Please tell me how to fix this speed issue!! When I rotate the shaft slowly, I can see the pulses increase nicely, 5120/4 at 90 degrees and 5120/2 at 180 degrees and so on. But when I do it fast it gives me small numbers, like 1000 pulses counted for a full rotation.
This is the code I am using:
#define encoderPinA 2
#define encoderPinB 3
volatile long encoderCount=0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(encoderPinA, INPUT_PULLUP);
pinMode(encoderPinB, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(encoderPinA),handleEncoder, RISING);
// attachInterrupt(digitalPinToInterrupt(encoderPinB),handleEncoder2, RISING);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(encoderCount);
delay(1000);
}
}
void handleEncoder() {
if (digitalRead(encoderPinA)>digitalRead(encoderPinB)){
encoderCount++;
}
else {
encoderCount--;
}
}
Look forward to fixing this!!
Best