|
| 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_motor import stepper as STEPPER |
| 10 | +from adafruit_motorkit import MotorKit |
| 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 | + move_dir = STEPPER.FORWARD |
| 40 | + print("forward") |
| 41 | + else: |
| 42 | + move_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, |
| 47 | + randomsteps, |
| 48 | + move_dir, |
| 49 | + stepstyles[random.randint(0,3)],)) |
| 50 | + st1.start() |
| 51 | + |
| 52 | + if not st2.isAlive(): |
| 53 | + print("Stepper 2") |
| 54 | + randomdir = random.randint(0, 1) |
| 55 | + if randomdir == 0: |
| 56 | + move_dir = STEPPER.FORWARD |
| 57 | + print("forward") |
| 58 | + else: |
| 59 | + move_dir = STEPPER.BACKWARD |
| 60 | + print("backward") |
| 61 | + randomsteps = random.randint(10,50) |
| 62 | + print("%d steps" % randomsteps) |
| 63 | + st2 = threading.Thread(target=stepper_worker, args=(kit.stepper2, |
| 64 | + randomsteps, |
| 65 | + move_dir, |
| 66 | + stepstyles[random.randint(0,3)],)) |
| 67 | + st2.start() |
| 68 | + |
| 69 | + time.sleep(0.1) # Small delay to stop from constantly polling threads |
| 70 | + # see: https://forums.adafruit.com/viewtopic.php?f=50&t=104354&p=562733#p562733 |
0 commit comments