Skip to content

Commit a4ab8ea

Browse files
committed
Add threaded dual stepper example
1 parent 6f2d8ad commit a4ab8ea

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

examples/DualStepperTest.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/python
2+
#
3+
# NOTE - Only for use on Raspberry Pi or other SBC.
4+
#
5+
import time
6+
import atexit
7+
import threading
8+
import random
9+
from adafruit_motorkit import MotorKit
10+
from adafruit_motor import stepper as STEPPER
11+
12+
# create a default object, no changes to I2C address or frequency
13+
kit = MotorKit()
14+
15+
# create empty threads (these will hold the stepper 1 and 2 threads)
16+
st1 = threading.Thread()
17+
st2 = threading.Thread()
18+
19+
# recommended for auto-disabling motors on shutdown!
20+
def turnOffMotors():
21+
kit.stepper1.release()
22+
kit.stepper2.release()
23+
24+
atexit.register(turnOffMotors)
25+
26+
stepstyles = [STEPPER.SINGLE, STEPPER.DOUBLE, STEPPER.INTERLEAVE, STEPPER.MICROSTEP]
27+
28+
def stepper_worker(stepper, numsteps, direction, style):
29+
#print("Steppin!")
30+
for _ in range(numsteps):
31+
stepper.onestep(direction=direction, style=style)
32+
#print("Done")
33+
34+
while (True):
35+
if not st1.isAlive():
36+
randomdir = random.randint(0, 1)
37+
print("Stepper 1"),
38+
if (randomdir == 0):
39+
dir = STEPPER.FORWARD
40+
print("forward"),
41+
else:
42+
dir = STEPPER.BACKWARD
43+
print("backward"),
44+
randomsteps = random.randint(10,50)
45+
print("%d steps" % randomsteps)
46+
st1 = threading.Thread(target=stepper_worker, args=(kit.stepper1, randomsteps, dir, stepstyles[random.randint(0,3)],))
47+
st1.start()
48+
49+
if not st2.isAlive():
50+
print("Stepper 2"),
51+
randomdir = random.randint(0, 1)
52+
if (randomdir == 0):
53+
dir = STEPPER.FORWARD
54+
print("forward"),
55+
else:
56+
dir = STEPPER.BACKWARD
57+
print("backward"),
58+
randomsteps = random.randint(10,50)
59+
print("%d steps" % randomsteps)
60+
st2 = threading.Thread(target=stepper_worker, args=(kit.stepper2, randomsteps, dir, stepstyles[random.randint(0,3)],))
61+
st2.start()
62+
63+
time.sleep(0.1) # Small delay to stop from constantly polling threads (see: https://forums.adafruit.com/viewtopic.php?f=50&t=104354&p=562733#p562733)

0 commit comments

Comments
 (0)