I am testing 400 PPR(Pulses Per Revolution) rotary encoder using code.I am rotating it by using the hand. I have connected Phase A and Phase B and also, ground and Vcc properly. The code is giving less than 400 counts in every rotation.eg. sometimes 385,350,360,390. Maximum time the range is in between 350 to 400. The code is given below:
#define PIN1 14
#define PIN2 10
volatile long pos;
volatile uint8_t state;
void pin_isr(void)
{
uint8_t p1val = digitalRead(PIN1);
uint8_t p2val = digitalRead(PIN2);
uint8_t s = state & 3;
if (p1val) s |= 4;
if (p2val) s |= 8;
state = (s >> 2);
switch (s) {
case 1: case 7: case 8: case 14:
pos++;
return;
case 2: case 4: case 11: case 13:
pos--;
return;
case 3: case 12:
pos += 2;
return;
case 6: case 9:
pos -= 2;
return;
}
}
int main(int argc, const char * argv[]) {
// sets up the wiringPi library
if (wiringPiSetup() < 0) {
perror("wiringPiSetup");
exit(EXIT_FAILURE);
}
pinMode (PIN1, INPUT) ;
pinMode (PIN2, INPUT) ;
pullUpDnControl(PIN1, PUD_UP);
pullUpDnControl(PIN2, PUD_UP);
if ( wiringPiISR (PIN1, INT_EDGE_BOTH, &pin_isr) < 0 ) {
perror("wiringPiISR");
exit(EXIT_FAILURE);
}
if ( wiringPiISR (PIN2, INT_EDGE_BOTH, &pin_isr) < 0 ) {
perror("wiringPiISR");
exit(EXIT_FAILURE);
}
// Show position every second
while ( 1 ) {
printf( "%ld\n", pos);
delay( 10 ); // wait 1 second
}
return 0;
}
I have written similar code for Arduino which perfectly working fine. Every time I am getting exactly 400 counts per rotation. Does anyone know what is the exact problem?