more backups
[rb-clock.git] / python / rotor-test3.py
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.
4
5 # Output looks like this:
6 #
7 #    A B STATE SEQ DELTA SWITCH
8 #    1 1   3    2    1    0
9 #    0 1   2    3    1    0
10 #    0 0   0    0    1    0
11 #    1 0   1    1    1    0
12 #    1 1   3    2    1    0
13 #    0 1   2    3    1    0
14
15 import gaugette.rotary_encoder
16 import gaugette.switch
17 import math
18
19 A_PIN  = 5
20 B_PIN  = 4
21 SW_PIN = 2
22
23 encoder = gaugette.rotary_encoder.RotaryEncoder(A_PIN, B_PIN)
24 switch = gaugette.switch.Switch(SW_PIN)
25
26 last_state = None
27 last_switch_state = None
28 last_delta = 0
29 last_sequence = encoder.rotation_sequence()
30 last_heading = 0
31
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.
40
41 while True:
42
43     state = encoder.rotation_state()
44     switch_state = switch.get_state()
45
46     if (state != last_state or switch_state != last_switch_state):
47         last_switch_state = switch_state
48         last_state = state
49
50         # print a heading every 20 lines
51         if last_heading % 20 == 0:
52           print "A B STATE SEQ DELTA SWITCH"
53         last_heading += 1
54
55         # extract individual signal bits for A and B
56         a_state = state & 0x01
57         b_state = (state & 0x02) >> 1
58
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
62
63         # compute delta:
64         # This is the same as the value returned by encoder.get_delta()
65         delta = (sequence - last_sequence) % 4
66         if delta == 3:
67             delta = -1
68         elif delta==2:
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))
73         last_delta = delta
74         last_sequence = sequence
75
76         print '%1d %1d %3d %4d %4d %4d' % (a_state, b_state, state, sequence, delta, switch_state)