简体   繁体   中英

Trying to use a string variable in serial .write in Python

I am communicating with a power supply through rs232. I can communicate no problem when I send for example:

port.write("\x31")

but if instead I have a string as a variable

teststring='"\\x31"'     

(which prints out as "\\x31")

and I try:

port.write(teststring)

it does not send the command to the supply. I have tried:

port.write(bytes(teststring,'utf-8'))

and

port.write(teststring.encode('utf-8'))

But it still is somehow not sending the same as just entering the text. I need to be able to change this variable, so I cannot just code the text in. Any help is appreciated!

Using comments below, I am now using an integer

testint=31 and if I print

chr(testint) I get a an odd box with 00 in the top row and 1F in the bottom. What I now need to be able to do is convert the 31 to 0x31, so I can use chr(0x31) which when printed produces 1. Hopefully the .write command will treat chr(0x31) the same as "\\x31" ?

teststring in your example is escaping the backslash; you have "\\\\x30" , instead of "\\x30" . "\\x30" is a length-1 string containing the byte 0x30; "\\\\x30" is a length-4 string containing the characters \\ , x , 3 and 0 . Dropping the first slash in teststring should behave exactly like using port.write("\\x30") .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM