-1

I copy this copy this code from github and try to run it on python. I got the following error. Im new to python and raspberry pi. Please someone sort this out?

Error:

if(bool(sys.argv[1]) and bool(sys.argv[2])): IndexError: list index out of range

coding:

import time
import RPi.GPIO as GPIO
import sys

GPIO.cleanup()

GPIO.setmode(GPIO.BCM)



Passed = 0


pulseWidth = 0.01


if(bool(sys.argv[1]) and bool(sys.argv[2])):

    try:
        motorPin = int(sys.argv[1])
        runTime = float(sys.argv[2])
        powerPercentage = float(sys.argv[3]) / 100
        Passed = 1
    except:
        exit

if Passed:

    # Set all pins as output
    print "Setup Motor Pin"
    GPIO.setup(motorPin,GPIO.OUT)
    GPIO.output(motorPin, False)
    counter = int(runTime / pulseWidth)

    print "Start Motor" 

    print "Power: " + str(powerPercentage)
    onTime = pulseWidth * powerPercentage
    offTime = pulseWidth - onTime

    while counter > 0:
        GPIO.output(motorPin, True)
        time.sleep(onTime)
        GPIO.output(motorPin, False)
        time.sleep(offTime)
        counter = counter - 1

    print "Stop Motor"
    GPIO.output(motorPin, False)


else:
        print "Usage: motor.py GPIO_Pin_Number Seconds_To_Turn Power_Percentage"

GPIO.cleanup()
user2728151
  • 1
  • 1
  • 1

2 Answers2

3

sys.argv contains a list of the command line arguments used to call the script, the first element of which will always be the name of your script. If you call the script without any arguments, it will only contain one element.

Since your code doesn't check to ensure it contains at least three element, calling the script with fewer than two arguments will try to access elements not in the list, raising the exception you see.

Cairnarvon
  • 25,981
  • 9
  • 51
  • 65
0

sys.argv is a list of of command line arguments passed to python script. argv[0] is script name, argv[1] first arg and so on... looks like you are calling the script without passing required arguments.

mkowalik
  • 133
  • 1
  • 9