简体   繁体   中英

Properly nesting loops with Python3 for a stepper motor

I'm trying to operate a stepper motor using a Raspberry Pi and adafruit Motor HAT, in order to turn a rod which lifts small water-filled pots. However I need to do this in slow stages, to allow water to drain out and prevent the system being too heavy for the motor.

I am trying to create a nested loop which performs a discrete number of steps, pauses for a period, then performs the loop again. I am having difficulty with pause element, as my attempts at nesting end up turning the motor off after the first rotation.

I can simulate the effect I want to achieve using the code below, but it is obviously bulky, inefficient and difficult to precisely fix the number of loops.

from adafruit_motorkit import MotorKit
from time import sleep

kit = MotorKit()

from adafruit_motor import stepper

for i in range(20):
        kit.stepper1.onestep(direction=stepper.BACKWARD, style=stepper.INTERLEAVE)

print("Turn")

sleep(10)

for i in range(20):
        kit.stepper1.onestep(direction=stepper.BACKWARD, style=stepper.INTERLEAVE)

print("Turn")

sleep(10)

for i in range(20):
        kit.stepper1.onestep(direction=stepper.BACKWARD, style=stepper.INTERLEAVE)

print("Turn")

for i in range(20):
        kit.stepper1.onestep(direction=stepper.BACKWARD, style=stepper.INTERLEAVE)

print("Turn")

sleep(10)

for i in range(20):
        kit.stepper1.onestep(direction=stepper.BACKWARD, style=stepper.INTERLEAVE)

print("Turn")

sleep(10)

for i in range(20):
        kit.stepper1.onestep(direction=stepper.BACKWARD, style=stepper.INTERLEAVE)

print("Turn") 

I would be very grateful for advice on how to properly nest the loop.

The code below should do exactly what you have got

from adafruit_motorkit import MotorKit
from time import sleep

kit = MotorKit()

from adafruit_motor import stepper
for j in range(6):
    for i in range(20):
        kit.stepper1.onestep(direction=stepper.BACKWARD, style=stepper.INTERLEAVE)

    print("Turn %s" % (j + 1))

    sleep(10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM