About a year ago, I posted an article about 2-channel rotary encoder interfacing with MCU using lookup table. With its linear program flow, inherent noise immunity and small processing requirements, this method produces extremely efficient code. The article attracted quite a bit of attention with many interesting comments and several code modifications. Today, I want to demonstrate slightly different way of reading the encoder – via interrupt service routine (ISR).
I’m currently involved in a project built with QP Event-Driven Real Time Framework running on 8-bit AVR micro. Rather than implementing periodic polling, I wanted to generate encoder events as they occur. AVR Atmega, as well as many other micros have external interrupt source called “Pin Change”, ideally suited for an encoder. As the name implies, pin change interrupt occurs when certain digital port pin changes state from low to high or vice versa. When an encoder is rotated, one pin changes state from say low to high, then other goes from low to high, than the first one goes from high to low, then the other one goes from high to low. The cycle then repeats. In order to properly react to every state change we want to be able to generate interrupt on every transition on each pin and that is exactly how pin change interrupt works.
I am developing for custom built AVR-based board and all code snippets are pasted directly from project files. This code can be used on bare metal Atmega as well as Arduino board with no changes and can also be adopted for other micros with only minor modifications, such as port and pin names. Encoder’s A and B pins are connected to Port B pins 0 and 1, common pin is connected to ground. To prevent floating inputs, internal pull-ups are turned on.
Continue reading Rotary encoder interrupt service routine for AVR micros