www.nutsvolts.com/index.php?/magazine/article/december2010_Kibalo
samples any of these output
waveforms and determines the
amount of rotation. If time is also
known, speed can be
determined, as well. The final
missing ingredient is the direction
of shaft rotation CW or CCW;
this is where both A and B
waveforms are used together.
Waveform A is the same no
matter what the direction of shaft
rotation is. Waveform B reverses
its order as the shaft turns from
CW to CWW. By sampling both
waveforms simultaneously and
comparing them against one
another, the microcontroller
determines the direction of rotation.
With a rotary encoder, the microcontroller can
determine direction, speed, and amount of rotation. All
three of these physical phenomena can be used for
operator input. For one of our demos, we will use the
rotary encoder rotations and direction to cause up/down
scrolling of text on the LCD display.
The specific encoder used in these demos is available
from SparkFun (part number COM-09117). This encoder
also has a built-in select switch (by pushing in on the
encoder knob). We will use all these features in our first
experiment.
■ FIGURE 2. Rotary
encoder CW and
CCW commutation.
Let’s Review the PIC24F
Peripheral Timer
We need the PIC24F timer peripheral and its interrupt
capability to work with the rotary encoder. We have
plenty of timers with the Experimenter — five total (Timer
1, Timer 2, Timer 3, Timer 4, and Timer 5). A timer high
level block diagram is shown in Figure 3.
Each element within the timer has its own set of
controls that the microcontroller needs to initialize.
Starting on the left side of the block diagram is the input
clock source selection for the timer controlled by TCS
(timer clock select bit). The TCS setting allows for either
the external clock or the internal PIC24F CPU clock. The
PIC24F internal clock is 16 MHz which is the clock we
will use for our demo.
The next control is Timer
Enable that turns on the
timer. The next stage is
the prescaler that allows
the clock to be scaled
down by factors of 1, 8,
64, and 256. The
prescaler is set using
an internal control register designated Timer Control
(T1CON for Timer 1). The final element within the block
diagram is the preset register and the timer register,
both of which are16 bits wide. The microcontroller writes
to the preset register to set the upper count range for the
timer. During timer operation, the preset value is
constantly compared against the running count value of
the timer for a match condition. If a match occurs, a
Timer Interrupt flag is latched to alert the microcontroller.
Another action that occurs as a result of this latch is the
reset of the timer register — this automatically starts the
next timing cycle.
■ FIGURE 3. PIC24F timer
generic block diagram.
December 2010 33