-3

Trying to run the below on an RPi to get a stepper motor to work properly. Many are able to run the code with no issues, but I get the following error. [Argument 3] should be within aSequence, but not sure why it is not picking it up. Any advice on how to fix it would be appreciated.

Traceback (most recent call last):
if sys.argv[3] == "cw":
IndexError: list index out of range

Code

import sys
import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)

aMotorPins = [12, 15, 11, 13]

for pin in aMotorPins:
    GPIO.setup(pin,GPIO.OUT)
    GPIO.output(pin, False)

aSequence = [
    [1,0,0,1],
    [1,0,0,0],
    [1,1,0,0],
    [0,1,0,0],
    [0,1,1,0],
    [0,0,1,0],
    [0,0,1,1],
    [0,0,0,1]
]

iNumSteps = len(aSequence)

if sys.argv[3] == "cw":
    iDirection = 1
else:
    iDirection = -1

fWaitTime = int(sys.argv[1]) / float(1000)

iDeg = int(int(sys.argv[2]) * 11.377777777777)

iSeqPos = 0
if len(sys.argv) > 4:
    iSeqPos = int(sys.argv[4])

Thank you for your help

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
xDell
  • 1
  • 3
    Does this answer your question? ["list index out of range" when using sys.argv\[1\]](https://stackoverflow.com/questions/15121717/list-index-out-of-range-when-using-sys-argv1) – Jacques Jul 16 '20 at 21:33
  • https://stackoverflow.com/questions/13263951/what-is-argv-and-what-does-it-do/39359625 – Macattack Jul 16 '20 at 21:35
  • "[Argument 3] should be within aSequence, but not sure why it is not picking it up." Well, did you see the part of the error message where it highlights the code `if sys.argv[3] == "cw":`? Notice how the list being used is **not** `aSequence`, but `sys.argv`? – Karl Knechtel Aug 09 '22 at 08:21

1 Answers1

1

This line:

if sys.argv[3] == "cw":

Assumes there are 4 args given and if there aren't then it errors out with an index error. Try using list.get as by default it returns None if that index is out of range:

if sys.argv.get(3) == "cw":

Or use a try/except block:

try:
    if sys.argv[3] == "cw":
        iDirection = 1
    else:
        iDirection = -1
except IndexError:
    pass

Or check if the length is correct first:

if len(sys.argv) >= 3:
    if sys.argv[3] == "cw":
        iDirection = 1
    else:
        iDirection = -1

Whichever fits your program best.

Jab
  • 26,853
  • 21
  • 75
  • 114