15

I know there has been a lot of discussion on this but I still have a question. I am trying to send hex values through pyserial to my device using pyserial

command="\x89\x45\x56"
ser.write(command)

However I keep getting an error saying string argument without encoding. Does anyone know how to solve this?

BladeRunner
  • 151
  • 1
  • 1
  • 4

6 Answers6

17
packet = bytearray()
packet.append(0x41)
packet.append(0x42)
packet.append(0x43)

ser.write(packet)
rjha94
  • 4,292
  • 3
  • 30
  • 37
  • I found this particularly helpful for sending code-page translated byte streams. Application uses old Code Page 437. – TomServo Jun 19 '22 at 16:15
8

From pySerial API documentation:

write(data) Write the bytes data to the port. This should be of type bytes (or compatible such as bytearray or memoryview). Unicode strings must be encoded (e.g. 'hello'.encode('utf-8').

Assuming you're working on Python 3 (you should), this is the way to send a single byte:

command = b'\x61' # 'a' character in hex
ser.write(command)

For several bytes:

command = b'\x48\x65\x6c\x6c\x6f' # 'Hello' string in hex
ser.write(command)
amartin1911
  • 512
  • 5
  • 11
3

I have had success sending hex values from a string like so:

input = '736e7000ae01FF'    
ser.write(input.decode("hex"))
print "sending",input.decode("hex")

>> sending snp «☺ 
jjz
  • 925
  • 1
  • 13
  • 21
1

If this is Python 3, it's probably treating your string as unicode, and doesn't know how to transform it. I think you probably mean to use bytes here:

command=b"\x89\x45\x56"
John Szakmeister
  • 44,691
  • 9
  • 89
  • 79
1

If you use Python 3 you can use a bytes object.

command=b"\x89\x45\x56"

From the error it looks like pyserial tries to convert a (your) string into a bytes object without specifying an encoding.

TobiMarg
  • 3,667
  • 1
  • 20
  • 25
0

Thanks,

Finally, I figure out how to read the specify region of binary file and send through uart (as flow control).

    binary_file = open("test_small.jpg", 'rb')
    filesize = getSize(binary_file)
    ser = serial.Serial('COM7', 115200, timeout=0.5)
    count = 0
    while (offset < filesize):
        binary_file.seek(offset, 0)
        ser.write(binary_file.read(MTU))
        offset = offset + MTU