I am trying to send a string variable contains the command.
Like this:
value="[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]"
self.s.write(serial.to_bytes(value))
The above one fails. Won't give any error.
But it's working when I send a value like this:
self.s.write(serial.to_bytes([0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]))
I also tried sending string like this:
self.s.write(serial.to_bytes(str(value)))
Still not working. Can someone please let me know how to send the value by storing in string?
I want to do this thing:
value="[0x"+anotherstring+",0x"+string2+"0x33, 0x0a]"
and send the value.
Thanks!
If passing a list of integers works for you then just convert your hexadecimal representations into integers and put them in a list.
Detailed steps:
Open a python interpreter
Import
serial
and open a serial port, call itser
.Copy the code below and paste it in the python interpreter:
The code:
command = '310a320a330a'
hex_values = ['0x' + command[0:2], '0x' + command[2:4],
'0x' + command[4:6], '0x' + command[6:8],
'0x' + command[8:10], '0x' + command[10:12]]
int_values = [int(h, base=16) for h in hex_values]
ser.write(serial.to_bytes(int_values))
It will have the same effect that just this:
ser.write(serial.to_bytes([0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]))
actually you can test that int_values == [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]
is True
so you are writing exactly the same thing.
serial.to_bytes takes a sequence as input. You should remove double quotes around value
to pass a sequence of integers instead of a str
representing the sequence you want to pass:
value = [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]
self.s.write(serial.to_bytes(value)) # works now
In the first case, you sent a sequence of bytes representing "[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]"
. Now, you will send the sequence [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]
as expected.
If you want to send a string, just send it as bytes
:
# Python 2
self.s.write('this is my string')
text = 'a string'
self.s.write(text)
# Python 3
self.s.write(b'this is my string')
text = 'a string'
self.s.write(text.encode())
And for a sequence:
for value in values:
# Python 2
self.s.write(value)
# Python 3
self.s.write(value.encode())
来源:https://stackoverflow.com/questions/39424865/sending-string-to-serial-to-bytes-not-working