我们正在尝试使用 Raspberry Pi 3b 和 8825 驱动器使步进电机工作。但是,我们使用的代码不起作用并产生错误。
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
control_pins = [14,15,18]
for pin in control_pins:
GPIO.setup(pin,GPIO.OUT)
GPIO.output(pin,0)
halfstep_seq = [
[0,0,0],
[0,0,1],
[0,1,0],
[0,1,1],
[1,0,0],
[1,0,1]
]
for i in range(512):
for halfstep in range(8):
for pin in range(4):
GPIO.output(control_pins[pin],halfstep_seq[halfstep][pin])
time.sleep(0.001)
GPIO.cleanup()
这是我们的控制台告诉我们的:
test_stepper.py:6: RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.
GPIO.setup(pin,GPIO.OUT) Traceback (most recent call last): File "test_stepper.py", line 19, in GPIO.output(control_pins[pin],halfstep_seq[halfstep][pin]) IndexError: list index out of range
请您参考如下方法:
halfstep_seq 中有 6 个步骤,其索引为 0 到 5。但稍后,您会:
for halfstep in range(8):
.... halfstep_seq[halfstep]...
因此 halfstep 将采用 0 到 7 之间的值,从而导致 IndexError。
同样,你有 3 个引脚,而不是 4 个。
所以,你的代码应该是:
for i in range(512):
for halfstep in range(6):
for pin in range(3):
GPIO.output(control_pins[pin],halfstep_seq[halfstep][pin])
但在 Python 中,最好在列表上迭代而不显式引用索引:
for halfstep in halfsteps:
for pin_num, pin_value in zip(control_pins, halfstep):
GPIO.output(pin_num, pin_value)
