switch input every millisecond.
A steady run of seven zeroes
following the last bounce reliably
signals the button has been clicked.
The encoder is more complex
because it has two pins to work
with at the same time, and either
the on or off states may be valid.
Every millisecond, a counter is
incremented for a stable sample
(i.e., the current value equals the
previous value). Otherwise, it is
decremented. This acts like a
capacitor filtering out any contact
bouncing. Once a number of stable
samples have been achieved, the
direction of rotation can be
determined. I found the best
responsiveness of the encoder and
reliable sampling by experimenting.
■ FIGURE 5.
■ FIGURE 6. Just five library functions provide all of the USB interaction
required by the main program.
The type of encoder specified in the Parts List is an
incremental encoder and requires some logic to figure out
if you are turning it clockwise or counterclockwise.
Direction is determined by “exclusive or-ing” the
encoder’s previous most significant bit with the current
least significant bit. Figure 5 shows the sequence
generated by the encoder in either direction.
To ensure the encoder logic reports the correct
direction after initial device reset, the previous encoder
value is initialized to the current port value during device
been initialized, the main loop waits for the device to be
configured, at which point the host begins regularly
polling the device’s endpoint. When the Windows host
goes into stand-by, a USB signal is sent to the device to
tell it to go into low power suspend mode. When the
device detects this state, the device turns off the
configured LED and executes the sleep instruction to halt
the CPU. Power consumption in this state is less than 0.5
milliamps. When the host resumes, the device
automatically wakes up and becomes operational.
The AT90USB162 does not come in a standard
The software provided includes
all of the functions needed to
manage the HID protocol and
switch interfacing. The module
UsbHid.c exposes all of the
functions needed to manage the
USB interface and are summarized
in Figure 6. The source code
supplied with this article shows
how to use the library.
Once the USB module has
■ FIGURE 7. Inside view.
The cable feeds through a hole
in the PCB to act as a strain relief
for the cable.
January 2012 41