Pololu Robotics & Electronics
Menu
My account Comments or questions? About Pololu Contact Ordering information Distributors

Pololu Forum

Help with a python code for Finding the Servo Positions


#1

So, I have this function coded in python that prints the servo positions (I attached it to the bottom). It works fine, but when I attempt to iterate this (i.e. a function that finds the positions, moves the servo, finds the new positions, moves the servo, etc.), the program will return incorrect values for every iteration beyond the first. Can someone tell me why this happens and possibly a solution to this problem? Thank you in advance.

[code]import serial
import time
import sys
def hi(ServoSerial):
comData=[0,0,0,0]
comData[0]=170
comData[1]=12
comData[2]=16
comData[3]=0
com1Data=[0,0,0,0]
com1Data[0]=170
com1Data[1]=12
com1Data[2]=16
com1Data[3]=1
com2Data=[0,0,0,0]
com2Data[0]=170
com2Data[1]=12
com2Data[2]=16
com2Data[3]=2

for i in range(1,3):
    if i==1:
        coms0data=bytearray(comData)
        coms1data=bytearray(com1Data)
        coms2data=bytearray(com2Data)
        serv1=ServoSerial.write(coms0data)
       
        serv2=ServoSerial.write(coms1data)
        serv2=ServoSerial.read(size=2)
        serv1=int.from_bytes(serv2,sys.byteorder)
        
    else:
        coms0data=bytearray(comData)
        coms1data=bytearray(com1Data)
        coms2data=bytearray(com2Data)
        
        
        serv2=ServoSerial.write(coms1data)
        serv2=ServoSerial.read(size=2)
        serv2=int.from_bytes(serv2,sys.byteorder)
        
serv1=int(serv1/4)
serv2=int(serv2/4)
print(serv1)
print(serv2)[/code]

#2

Also, I know the script is repetitive and some of it can be removed; I’m fixing that later. I just need to know why trying to iterate getting the position is not working.


#3

Never mind, I figure it out, and it was quite obvious: I was clearing out my output buffer. I won’t take down this post just in case somebody needs it in the future.


#4

Hello.

I am glad you found the issue and fixed it; thank you for letting us know.

By the way, before your recent post I briefly looked at you code and noticed in several places that you assign the return value from pyserial’s write method to a variable, which is not used in your code. You do not need to assign the return value to a variable if you are not going to use it.

Also, you might consider using maestro.py, a Python class that controls the Maestro over its serial interface, which was created and shared by one of our forum members. The source code is linked under the “Related Resources” section of the Maestro User’s Guide.

- Amanda