Python Forum

Full Version: making a function that writes variables (is possible?)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I'm running dynamixel servos and I tried to convert few lines of code that read packet into a function to shorten the lines.
the lines were like this:


        dxl_present_position, dxl_comm_result, dxl_error = packetHandler.read4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_PRESENT_POSITION)
        if dxl_comm_result != COMM_SUCCESS:
            print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
        elif dxl_error != 0:
            print("%s" % packetHandler.getRxPacketError(dxl_error))
as it seems the "dxl_present_position" is used as a variable name later
print("[ID:%03d] GoalPos:%03d  PresPos:%03d" % (DXL_ID, dxl_goal_position[index], dxl_present_position))
but if I turn it into a function like this:
def readpacket(varname, id, address):
        varname, dxl_comm_result, dxl_error = packetHandler.read4ByteTxRx(portHandler, id, address)
        if dxl_comm_result != COMM_SUCCESS:
            print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
        elif dxl_error != 0:
            print("%s" % packetHandler.getRxPacketError(dxl_error))

readpacket(present_position, 1, 136) # 1 is the servo id, 136 is the prespos address
returns error "present_position is not defined"
outside a function it works just fine..
so I would like to know, maybe its just impossible in python setting variables using a function, if there is a similar approach that'd be great.
thanks in advance!
here is a dynamixel sdk github link:
dynamixel sdk github
ps: i'm kind of a beginner, so sry if I make newbie mistakes, thanks
isn't it dxl_present_position?
(Jan-30-2020, 05:50 PM)buran Wrote: [ -> ]isn't it dxl_present_position?

dxl_present_position is a variable that you choose. I just wrote "present_position" instead just for the sake of showing the possibility of being flexible with the function I'm trying to make. in the printing it'll be
print("[ID:%03d] GoalPos:%03d  PresPos:%03d" % (DXL_ID, dxl_goal_position[index], present_position))
if this is what you mean
I mean that we don't know where you get that variable (whatever its name is) that you pass when call the function.
In other words - the function definition has nothing to do with the problem that a name you pass as argument is not defined.
the name should be defined in your code before you pass it as argument on line 8 in the third snippet.

my suggestion was based on the fact that in your original code (without function) it worked an I decided that it's just a typo that cause the error