2

We're trying to make a stepper motor work using a Raspberry Pi 3b and the 8825 driver. However, the code we're using doesn't work and produces an error.

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()

This is what our console has told us:

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

1 Answer 1

1

You have 6 steps in halfstep_seq, whose indices will be 0 to 5. But later, you do:

for halfstep in range(8):
    .... halfstep_seq[halfstep]...

so halfstep will take values from 0 to 7, causing an IndexError.

Similarly, you have 3 pins, not 4.

So, your code should be:

for i in range(512):
    for halfstep in range(6):
        for pin in range(3):
            GPIO.output(control_pins[pin],halfstep_seq[halfstep][pin])

But in Python, it is better to iterate on lists without explicitely referring to the indices:

  for halfstep in halfsteps:
    for pin_num, pin_value in zip(control_pins, halfstep):
      GPIO.output(pin_num, pin_value)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.