Hardware Reference
In-Depth Information
Listing 15-2 Rotary Encoder Testing
#!/usr/bin/env python
“””
Rotary Encoder input test 2 - show count
encoder wired to inputs 6 & 7
“””
import piface.pfio as pfio # piface library
pfio.init() # initialise piface
print “Single encoder input test Ctrl C to quit”
print “Displays accumulated count for X control”
lastEncoder = pfio.read_input() & 0xC0
count = 0
while True:
encoder = pfio.read_input() & 0xC0
if lastEncoder != encoder and (lastEncoder == 0 or ;
lastEncoder == 0xC0):
if (lastEncoder == 0 and encoder == 0x80) or ;
(lastEncoder == 0xC0 and encoder == 0x40) :
count -=1
if (lastEncoder == 0xC0 and encoder == 0x80) or ;
(lastEncoder == 0 and encoder == 0x40) :
count +=1
print count
lastEncoder = encoder
When you study the listing you will see that what happens here is that once the encoder is read,
the values are passed into an if statement that looks for the condition of the last encoder read-
ing being in one of the two detent positions, and the current reading not being the same as the
last reading. In other words the encoder has just moved from its rest position. Now you see in
what direction it has turned by looking at the current reading in conjunction with the last read-
ing. here are two possible readings for an anticlockwise motion depending on the previous
reading; if either of these two conditions is met then a count is decremented. Similarly for a
clockwise movement there are two possible previous and current combinations indicating a
click. Notice that the position is printed out independently of either clockwise or anticlockwise
rotation being detected. his means that if you see two numbers the same printed out consecu-
tively, then there has been a contact bounce reading that has resulted in an error which has
been ignored. You will notice that the values compared with those from the encoder are hard
coded. hat is, they refer only to that one encoder wired in the top two bits of the input. In
order to make things more eicient you can shift the bits you are interested in into the lowest
two bits and use the same code for reading both encoders.
 
Search WWH ::




Custom Search