■ FIGURE 4. Timer
■ FIGURE 5. Timer
interrupt service template.
■ FIGURE 6. Rotary encoder display demo.
other parts of the program, then this communication must
occur through the use of shared variables.
Interrupt functions accept no parameters and return
no parameters (note the use of void), and each interrupt
source has its own specific function call. The code that
executes during an interrupt function is called the
“interrupt service routine.” General recommendations for
writing an interrupt service are: First, perform the minimal
essential processing needed for the service (that is, get in
and out quickly); and secondly, do not call any other
functions during the service. Finally, an interrupt service
must reset the original interrupt flag that initiated the interrupt
before exiting. If the interrupt service communicates with
Interfacing to a Rotary Encoder
Using Timer 1
For this demo, we use Timer1 with interrupt service to
process rotary encoder outputs. As the encoder knob is
turned, the Experimenter LCD displays the direction and
amount of rotation of the encoder. In addition, the display
also shows the condition of the SELECT switch (that is part
of the encoder) as ON or OFF, depending on whether you
push in the knob. The demo uses the LCD library that was
discussed in previous Experimenter
articles. Figure 6 shows the LCD display.
The hook-up diagram is shown in
Figure 9. The demo in Figure 8 is an
excellent way to test your rotary
encoder and verify its proper operation.
Let’s take a closer look at the
interrupt service. With a continuous
five millisecond interrupt, the interrupt
service code samples Output A and
determines if it is changing in value
from previous samples or remaining
the same. If A goes high to low, the
code will then look at Output B and
make a determination on direction. Only
during CCW operation — when A goes
high to low — will Output B be zero. If
this CCW condition is not detected,
the rotation direction defaults to CW.
In all cases where Output A changes
from a low to a high, the condition will
count as a detent movement.
The interrupt service reports the
current encoder position and rotation
using two variables: (D for direction (1 =
CW, -1 = CCW) and RCOUNT (rotational
count). RCOUNT will increment or
■ FIGURE 7. Timer1
interrupt service routine.