简体   繁体   English

使用 Python3 为步进电机正确嵌套循环

[英]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.我正在尝试使用 Raspberry Pi 和 adafruit Motor HAT 来操作步进电机,以转动一根杆来提升小型充水罐。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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