1 # Sample code for both the RotaryEncoder class and the Switch class.
2 # The common pin for the encoder should be wired to ground.
3 # The sw_pin should be shorted to ground by the switch.
5 # Output looks like this:
7 # A B STATE SEQ DELTA SWITCH
15 import gaugette.rotary_encoder
16 import gaugette.switch
23 encoder = gaugette.rotary_encoder.RotaryEncoder(A_PIN, B_PIN)
24 switch = gaugette.switch.Switch(SW_PIN)
27 last_switch_state = None
29 last_sequence = encoder.rotation_sequence()
32 # NOTE: the library includes individual calls to get
33 # the rotation_state, rotation_sequence and delta values.
34 # However this demo only reads the rotation_state and locally
35 # derives the rotation_sequence and delta. This ensures that
36 # the derived values are based on the same two input bits A and B.
37 # If we used the library calls, there is a very real chance that
38 # the inputs would change while we were sampling, giving us
39 # inconsistent values in the output table.
43 state = encoder.rotation_state()
44 switch_state = switch.get_state()
46 if (state != last_state or switch_state != last_switch_state):
47 last_switch_state = switch_state
50 # print a heading every 20 lines
51 if last_heading % 20 == 0:
52 print "A B STATE SEQ DELTA SWITCH"
55 # extract individual signal bits for A and B
56 a_state = state & 0x01
57 b_state = (state & 0x02) >> 1
59 # compute sequence number:
60 # This is the same as the value returned by encoder.rotation_sequence()
61 sequence = (a_state ^ b_state) | b_state << 1
64 # This is the same as the value returned by encoder.get_delta()
65 delta = (sequence - last_sequence) % 4
69 # this is an attempt to make sense out of a missed step:
70 # assume that we have moved two steps in the same direction
71 # that we were previously moving.
72 delta = int(math.copysign(delta, last_delta))
74 last_sequence = sequence
76 print '%1d %1d %3d %4d %4d %4d' % (a_state, b_state, state, sequence, delta, switch_state)