Re-evaluating a string?

John Machin sjmachin at lexicon.net
Sun Jul 23 20:19:32 EDT 2006


bugnthecode wrote:
> I'm writing a program to send data over the serial port. I'm using
> pyserial, and I'm on WindowsXP. When I use literals I can get the data
> accross how I want it for example:
>
>                    1     2      3      4     5      6
> serialport.write('!SC'+'\x01'+'\x05'+'\xFA'+'\x00'+'\r')
>
> 1=Get devices attention
> 2=Select channel on device
> 3=Rate for movement
> 4=Low byte of 16 bits
> 5=High bytes of 16 bits
> 6=Carriage return signaling command is over
>
> This command works as desired. Sends the first 3 ASCII characters, then
> some numbers in hex followed by a carriage return.
>
> My problem is that the "write()" function only takes a string, and I
> want to substitute variables for the hex literals.
>
> I know that I can use the "hex()" function and it will return a string
> with the appropriate hex value, and I could combine this with some
> other literals like "\\" to create my desired hex literal, but then I
> would need something to re-parse my string to change my ASCII text into
> the appropriate hex values.

No need. That would be like travelling from Brooklyn to the Bronx via
Walla Walla, WA. And "the appropriate hex values" exist only as ASCII
text, anyway.

The following code (a) is untested (b) assumes each of the 3 numbers
(channel, rate, value) is UNsigned.

channel = 1
rate = 5
value = 0xFA # or value = 250
if HARD_WAY:
    vhi, vlo = divmod(value, 256)
    command = "!SC" + chr(channel) + chr(rate) + chr(vlo) + chr(vhi) +
"\r"
elif MEDIUM_WAY:
    vhi, vlo = divmod(value, 256)
    command = "!SC%c%c%c%c\r" % (channel, rate, vlo, vhi)
else:
    import struct
    command = "!SC" + struct.pack("<BBH", channel, rate, value) + "\r"
print repr(command) # for debugging, or if you're desperate to see some
hex values :-)
serialport.write(command)

Do check out the manual sections relating to the struct module.

If any value is signed, you definitely want to use the struct module
(with "b" or "h" instead of "B" or "H" of course) instead of mucking
about byte-bashing.

HTH,
John




More information about the Python-list mailing list