-
Notifications
You must be signed in to change notification settings - Fork 4
/
motor.py
109 lines (82 loc) · 2.34 KB
/
motor.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import machine
import time
# Thanks to:
# https://youtu.be/B86nqDRskVU
class Motor:
stepms = 10
# Do be defined by subclasses
maxpos = 0
states = []
def __init__(self, p1, p2, p3, p4, stepms=None):
self.pins = [p1, p2, p3, p4]
if stepms is not None:
self.stepms = stepms
self._state = 0
self._pos = 0
def __repr__(self):
return '<{} @ {}>'.format(
self.__class__.__name__,
self.pos,
)
@property
def pos(self):
return self._pos
@classmethod
def frompins(cls, *pins, **kwargs):
return cls(*[machine.Pin(pin, machine.Pin.OUT) for pin in pins],
**kwargs)
def zero(self):
self._pos = 0
def _step(self, dir):
state = self.states[self._state]
for i, val in enumerate(state):
self.pins[i].value(val)
self._state = (self._state + dir) % len(self.states)
self._pos = (self._pos + dir) % self.maxpos
def step(self, steps):
dir = 1 if steps >= 0 else -1
steps = abs(steps)
for _ in range(steps):
t_start = time.ticks_ms()
self._step(dir)
t_end = time.ticks_ms()
t_delta = time.ticks_diff(t_end, t_start)
time.sleep_ms(self.stepms - t_delta)
def step_until(self, target, dir=None):
if target < 0 or target > self.maxpos:
raise ValueError(target)
if dir is None:
dir = 1 if target > self._pos else -1
if abs(target - self._pos) > self.maxpos/2:
dir = -dir
while True:
if self._pos == target:
break
self.step(dir)
def step_until_angle(self, angle, dir=None):
if angle < 0 or angle > 360:
raise ValueError(angle)
target = int(angle / 360 * self.maxpos)
self.step_until(target, dir=dir)
class FullStepMotor(Motor):
stepms = 5
maxpos = 2048
states = [
[1, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 1],
[1, 0, 0, 1],
]
class HalfStepMotor(Motor):
stepms = 3
maxpos = 4096
states = [
[1, 0, 0, 0],
[1, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1],
[1, 0, 0, 1],
]