I am trying to send some data by an xbee from pc to arduino.
I have a test packet which I know it well built which is:
7E 00 7D 33 10 01 00 7D 33 A2 00 40 69 76 DD FF FE 00 00 01 52 B8 DA 41 1A
If I use:
ser.write(b'\x7E\x00\x7D\x33\x10\x01\x00\x7D\x33\xA2\x00\x40\x69\x76\xDD\xFF\xFE\x00\x00\x01\x52\xB8\xDA\x41\x1A')
My packet arrives to arduino.
But now I want to pass this packet by command line. Something like:
python test.py '\x7E\x00\x7D\x33\x10\x01\x00\x7D\x33\xA2\x00\x40\x69\x76\xDD\xFF\xFE\x00\x00\x01\x52\xB8\xDA\x41\x1A'
Being able this way to change data every time I want.
I tried with:
ser.write(sys.argv[1])
ser.write(sys.argv[1].encode('ascii'))
And other tries but always fails.
Any idea about how I have to pass the data? I think the problem is related to the initial b in ser.write...
I am using python 2.6 or 2.7... Not 3.
This works, but I have a feeling there's a better solution (there was; see the edit) :
import ast
import sys
ser.write(ast.literal_eval("'{0}'".format(sys.argv[1])))
We use the safe literal_eval
from the ast
module to evaulate the string "'\\x7E\\x00\\x7D...'"
as a python literal, which gets us what we want.
EDIT: Ah- hah! Found a better solution here :
ser.write(sys.argv[1].decode("string-escape"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.