-
Notifications
You must be signed in to change notification settings - Fork 1
/
encoders_test.py
67 lines (54 loc) · 2.24 KB
/
encoders_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# encoders_test.py
from time import sleep
from machine import Pin
# YOU MAY TEST
#from machine import Encoder # encoder based on hardware counters from ESP32, mimxrt, STM32 ports
#OR
from encoder_state import Encoder # https://github.com/IhorNehrutsa/MicroPython-quadrature-incremental-encoder/blob/main/encoder_state.py
# OR
#from encoder_portable import Encoder # https://github.com/peterhinch/micropython-samples/blob/master/encoders/encoder_portable.py
# OR
#from encoder_timed import EncoderTimed as Encoder # https://github.com/peterhinch/micropython-samples/blob/master/encoders/encoder_timed.py
# OR
#from encoder import Encoder # suitable for old Pyboard-specific version # https://github.com/peterhinch/micropython-samples/blob/master/encoders/encoder.py
# Define an Encoder pins
ENCODER_DATA = 16 # as input A
ENCODER_CLK = 17 # as input B
ENCODER_SW = 18 # as "index" input, typically labeled Z
PPR = 30 # pulses per revolution of the encoder shaft
try:
data = Pin(ENCODER_DATA, mode=Pin.IN, pull=Pin.PULL_UP)
clk = Pin(ENCODER_CLK, mode=Pin.IN, pull=Pin.PULL_UP)
sw = Pin(ENCODER_SW, mode=Pin.IN, pull=Pin.PULL_UP)
print('data as A', data, data.value())
print('clk as B', clk, clk.value())
print('sw as Z', sw, sw.value())
enc = Encoder(data, clk, scale=360 / PPR) # degreses
#enc = Encoder(data, clk, scale=2*3.141592/PPR) # radians
#enc = Encoder(data, clk, scale=1/PPR) # rotations
print(enc)
_data = None
_clk = None
_sw = None
_value = None
while True:
__data = data.value()
__clk = clk.value()
__sw = sw.value()
__value = enc.value()
_scaled = enc.scaled()
if (_data != __data) or (_clk != __clk) or (_sw != __sw) or (_value != __value):
_data = __data
_clk = __clk
_sw = __sw
_value = __value
if _sw == 0:
enc.set_value(PPR * round(enc.value() / PPR))
print("data={}, clk={}, sw={}, value={:10}, scaled={:13.2f}".format(_data, _clk, _sw, _value, _scaled), end=' \r')
sleep(0.1)
finally:
try:
# use enc.deinit(), otherwise enc._callback() will work after exiting the program
enc.deinit()
except:
pass