/ examples / motorkit_dual_stepper_test.py
motorkit_dual_stepper_test.py
 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  import board
10  from adafruit_motor import stepper as STEPPER
11  from adafruit_motorkit import MotorKit
12  
13  # create a default object, no changes to I2C address or frequency
14  kit = MotorKit(i2c=board.I2C())
15  
16  # create empty threads (these will hold the stepper 1 and 2 threads)
17  st1 = threading.Thread()  # pylint: disable=bad-thread-instantiation
18  st2 = threading.Thread()  # pylint: disable=bad-thread-instantiation
19  
20  
21  # recommended for auto-disabling motors on shutdown!
22  def turnOffMotors():
23      kit.stepper1.release()
24      kit.stepper2.release()
25  
26  
27  atexit.register(turnOffMotors)
28  
29  stepstyles = [STEPPER.SINGLE, STEPPER.DOUBLE, STEPPER.INTERLEAVE, STEPPER.MICROSTEP]
30  
31  
32  def stepper_worker(stepper, numsteps, direction, style):
33      # print("Steppin!")
34      for _ in range(numsteps):
35          stepper.onestep(direction=direction, style=style)
36      # print("Done")
37  
38  
39  while True:
40      if not st1.isAlive():
41          randomdir = random.randint(0, 1)
42          print("Stepper 1")
43          if randomdir == 0:
44              move_dir = STEPPER.FORWARD
45              print("forward")
46          else:
47              move_dir = STEPPER.BACKWARD
48              print("backward")
49          randomsteps = random.randint(10, 50)
50          print("%d steps" % randomsteps)
51          st1 = threading.Thread(
52              target=stepper_worker,
53              args=(
54                  kit.stepper1,
55                  randomsteps,
56                  move_dir,
57                  stepstyles[random.randint(0, 3)],
58              ),
59          )
60          st1.start()
61  
62      if not st2.isAlive():
63          print("Stepper 2")
64          randomdir = random.randint(0, 1)
65          if randomdir == 0:
66              move_dir = STEPPER.FORWARD
67              print("forward")
68          else:
69              move_dir = STEPPER.BACKWARD
70              print("backward")
71          randomsteps = random.randint(10, 50)
72          print("%d steps" % randomsteps)
73          st2 = threading.Thread(
74              target=stepper_worker,
75              args=(
76                  kit.stepper2,
77                  randomsteps,
78                  move_dir,
79                  stepstyles[random.randint(0, 3)],
80              ),
81          )
82          st2.start()
83  
84      time.sleep(0.1)  # Small delay to stop from constantly polling threads
85      # see: https://forums.adafruit.com/viewtopic.php?f=50&t=104354&p=562733#p562733