Re-evaluating a string?

bugnthecode bugnthecode at gmail.com
Sun Jul 23 20:44:51 EDT 2006


Thanks Tim, and John for your quick responses!

Tim, I tested your function and it works! Though I don't completely
understand how. Could you possibly explain this?

John, I test your "MEDUIM_WAY"and it works as well. How is it that
putting the string together this way translates into a hex value to be
transmitted to the serial port? When I manually tried to put a string
together I couldn't get this to happen. I was trying:

controlString = '!SC' + '\\' + ch.__str__() + '\\' + rate.__str__()
...etc

also I noticed you added another line to the code which appears to
split the low and high bytes for me? If so thanks! Could you also offer
an explanation on how this works. I tried a google search and couldn't
get a decent explanation. I implemented this a little differently as
you can see in my Position class. Could you possibly offer any info on
the benefits/drawbacks of the different methods?

Thanks again to both of you for your quick responses and help.

Will

import serial
import types

class Position:
    def __init__(self, num):
        """Takes the position as an int, and splits the low and high
bytes

        into instance members."""
        self.lowByte = num & 0x00FF
        self.highByte = (num & 0xFF00) >> 8

    def __str__(self):
        """Mainly for debugging purposes. Allows meaningful output when
printed"""
        return 'Low: ' + self.lowByte.__str__() + '\nHigh: ' +
self.highByte.__str__()

def makeString(a):
    """Takes in  a list, and intelligentlly smashes everything
together.

    Outputs everything as a hex string.
    Posted by: Tim Chase on comp.lang.python"""
    return ''.join([type(x) != types.IntType and
    str(x) or chr(x) for x in a])

def getVer(localpsc):
    """Gets the version from the PSC. Mainly just to verify a
connection"""

    localpsc.write('!SCVER?\r')
    localpsc.read(8) #Discard the echo!
    s = localpsc.read(3)
    print s

def moveServo(localpsc, ch, rate, position):
    """Takes in a serial object, the desired channel, the ramp rate,
and
    the desired position of ther servo. Moves the servo to the desired
postion."""

    #localpsc.write('!SC', ch, rate, position.low, position.high, '\r')
    #controlString = makeString(['!SC', ch, rate, position.lowByte,
position.highByte, '\r'])
    #localpsc.write(controlString)
    #localpsc.flushInput() #discard the echo!

    """Following line from John Machin"""
    controlString = "!SC%c%c%c%c\r" % (ch, rate, position.lowByte,
position.highByte)
    localpsc.write(controlString)

psc = serial.Serial(1, 2400)

mypos = Position(2500)

moveServo(psc, 0, 5, mypos)
psc.close()




More information about the Python-list mailing list