You only need two signals. A and B.
1. Use one of them (lets call it A) to trigger an edge INT interrupt.
2. In the ISR, read 'B', it tells you the direction
3. change your 'counter' value accordingly.
If you also want to incorporate acceleration, reset a timer at each interrupt and look at it's value on the next interrupt. If it is small enough (= rotating fast) add more to the counter.
You have a serious confusion with RB1_bit and EncoderA_bit respectively RB2_bit and EncoderB_bit. Encoderxx is defined as alias of the RBx, but should be a variable holding the previous input state.
Apart form this problem, the code should work. There's a possible complication with bouncing encoder outputs, RB1 and RB2 should be better copied to variables first, so that all instructions referring to it are using the same value.
The XOR logic and INT input can be saved by using Port B interrupt an change function.
You only need two signals. A and B.
1. Use one of them (lets call it A) to trigger an edge INT interrupt.
2. In the ISR, read 'B', it tells you the direction
3. change your 'counter' value accordingly.
Possible, but at the expense of loosing 3 of 4 available encoder steps. The simple logic also can't handle encoder rotated back and forth and gives potentially wrong counts.
Thanks all. Betwixt's method works fine. I don't need acceleration or position control. I am just using Rotary Encoder to select 4 different PWM frequencies for DC-DC Converter.
I removed the XOR gate and connected A to RB0/INT and B to RB1 and read in ISR.
Code is working fine now.
I need a little modification and I don't know how to implement it.
The rotary encoder has one more signal connection that is:
SW pin and it is used to provide signal for rotary encoder button press.
I want to know how I can connect
A
B
SW pins to PIC16F877A.
A needs INT pin
B needs DigitalInput pin
SW needs INT pin
and I have only one INT pin and I can't change the controller.
I need to use same INT pin for A and SW signals and counter should not increment when SW signals is given.
I agree with Klaus, you would need significant extra electronics to externally multiplex SW with the encoder output and for such a low priority function it isn't worth the extra effort. Just connect SW to another digital input and poll it.
How about using RB4 to RB7 interrupt on change function?
Key detection needs only moderate scan rate, it's very unusual to use interrupt for it. Incremental decoder depends on the application, pulse rate can be between a few Hz and 10s of kHz.