I'm trying to create a python class to control stepper motors using my Raspberry Pi. It mostly works, however I keep on getting an "'instancemethod' object has no attribute '__getitem__'
error whenever I define a list as a class variable. The error message lists this piece of code as the culprit but I can't see anything wrong with it if seq[self.StepCounter][pin]!=0:. It will work if I define it as an instance variable or a global variable though.
This is my code:
import RPi.GPIO as GPIO
import time
debug = True
class stepper:
clockwise = []
clockwise = range(0,4)
clockwise[0] = [1,0,0,0]
clockwise[1] = [0,1,0,0]
clockwise[2] = [0,0,1,0]
clockwise[3] = [0,0,0,1]
def __init__(self,pin1,pin2,pin3,pin4):
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
self.pin1 = pin1
self.pin2 = pin2
self.pin3 = pin3
self.pin4 = pin4
self.StepCounter = 0
self.pinarray = [pin1,pin2,pin3,pin4]
for pin in self.pinarray:
if debug == True:
print "Setup pin " + str(pin)
GPIO.setup(pin,GPIO.OUT)
GPIO.output(pin, False)
self.stepNum = 512.0
self.coilNum = 4.0
def setup(self,stepNum,coilNum):
self.stepNum = float(stepNum)
self.coilNum = float(coilNum)
self.partNum = self.coilNum * self.stepNum
def clockwise(self,speed):
seq = stepper.clockwise
self.WaitTime = (1.0 / (self.stepNum * self.coilNum)) * speed
for pin in range(0, 4):
xpin = self.pinarray[pin]
if seq[self.StepCounter][pin]!=0:
GPIO.output(xpin, True)
else:
GPIO.output(xpin, False)
self.StepCounter += 1
if (self.StepCounter==len(seq)):
self.StepCounter = 0
if (self.StepCounter<0):
self.StepCounter = len(seq)
time.sleep(self.WaitTime)
print "Adding Motor Instance"
motor = stepper(24,25,8,7)
print "Spinning Motor"
while "True":
motor.clockwise(5)
Please could someone tell me what's wrong with it and explain why. Thanks
You didn't post the full traceback, but I can take a guess:
def clockwise(self,speed):
seq = stepper.clockwise
self.WaitTime = (1.0 / (self.stepNum * self.coilNum)) * speed
for pin in range(0, 4):
xpin = self.pinarray[pin]
if seq[self.StepCounter][pin]!=0:
You set seq
equal to the method stepper.clockwise
on the first line. Then a few lines later you try to index into it: seq[self.StepCounter]
. But what does it mean to get the self.StepCounter
-th element of a method?
Nothing, because:
'instancemethod' object has no attribute '__getitem__'
You shouldn't use clockwise
both as the name of a list and as the name of a method; only the last-executed definition will hold, so by the time you get to seq = stepper.clockwise
, it's the method, not the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With