Skip to content

Add threaded dual stepper example #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 1, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions examples/DualStepperTest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#!/usr/bin/python
#
# NOTE - Only for use on Raspberry Pi or other SBC.
#
import time
import atexit
import threading
import random
from adafruit_motor import stepper as STEPPER
from adafruit_motorkit import MotorKit

# create a default object, no changes to I2C address or frequency
kit = MotorKit()

# create empty threads (these will hold the stepper 1 and 2 threads)
st1 = threading.Thread()
st2 = threading.Thread()

# recommended for auto-disabling motors on shutdown!
def turnOffMotors():
kit.stepper1.release()
kit.stepper2.release()

atexit.register(turnOffMotors)

stepstyles = [STEPPER.SINGLE, STEPPER.DOUBLE, STEPPER.INTERLEAVE, STEPPER.MICROSTEP]

def stepper_worker(stepper, numsteps, direction, style):
#print("Steppin!")
for _ in range(numsteps):
stepper.onestep(direction=direction, style=style)
#print("Done")

while True:
if not st1.isAlive():
randomdir = random.randint(0, 1)
print("Stepper 1")
if randomdir == 0:
move_dir = STEPPER.FORWARD
print("forward")
else:
move_dir = STEPPER.BACKWARD
print("backward")
randomsteps = random.randint(10,50)
print("%d steps" % randomsteps)
st1 = threading.Thread(target=stepper_worker, args=(kit.stepper1,
randomsteps,
move_dir,
stepstyles[random.randint(0,3)],))
st1.start()

if not st2.isAlive():
print("Stepper 2")
randomdir = random.randint(0, 1)
if randomdir == 0:
move_dir = STEPPER.FORWARD
print("forward")
else:
move_dir = STEPPER.BACKWARD
print("backward")
randomsteps = random.randint(10,50)
print("%d steps" % randomsteps)
st2 = threading.Thread(target=stepper_worker, args=(kit.stepper2,
randomsteps,
move_dir,
stepstyles[random.randint(0,3)],))
st2.start()

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