of course, no reason why the bit order could not
be reversed and the output sequence changed
correspondingly.)
To produce a number in the sequence shown, place
Outputs A and B in a byte in working storage like this:
bit 7
0
0
0
0
0
0
B
bit 0
A
At startup, the program must read the encoder value,
since it could output any of its four values. The value is
saved in memory as the previous value. The encoder is
then polled until the value changes. Comparing the
previous value and current value to the sequence 0, 1, 3,
2, you can tell which way the shaft has been rotated and
act accordingly. Then the current value is saved as the
previous value and polling continues.
Note that the encoder outputs require pullup resistors.
In my demonstration example, I use the internal pullups
available at port B of the PIC16F84A for the encoder and
the pushbutton. Otherwise, 10K resistors to the +5V
supply are recommended.
The pushbutton is debounced and read like any
pushbutton. According to the specifications, the longest
settle time is 10 milliseconds — which is pretty fast — so
your code can be responsive to button presses.
Finally, the encoder supply pin requires a 150 ohm
resistor between it and the +5V supply. The encoder’s
pinouts are shown in Table 1.
Pin
1
2
3
4
5
6
Description
Supply (+ 5 VDC through a 150 ohm resistor)
Ground
Output B
Output A
Pushbutton
Pushbutton
■ TABLE 1
■ FIGURE 3.
Pin numbers
viewed from
the top.
What Can I Do
With It?
The obvious use of the
encoder is for the clockwise rotation to
signal an “up” type event, the counter-clockwise rotation “down,” and the
pushbutton to signal some kind of
request or mode selection. For example, let’s say you are
designing a programmable thermostat with an LCD
readout. You want it to control either a furnace or air
conditioner, so it has three states: cool, heat, and off. You
could use up and down buttons for the temperature, and
a three position switch for the state. Or, you could use
an encoder. Rotating the shaft raises or lowers the
temperature setting. Pressing the button changes the
mode, activating a menu which allows you to select heat,
cool, or off (by rotating the shaft). Pressing the button
■ FIGURE 4.
Demo project
schematic.
August 2008 53