16

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?

2
  • 2
    Why not use binascii? from binascii import unhexlify, and then command = unhexlify("894556") Commented Jul 11, 2013 at 9:37
  • What version of Python are you using? And what's the full traceback look like? Commented Jul 11, 2013 at 10:11

6 Answers 6

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

ser.write(packet)
Sign up to request clarification or add additional context in comments.

1 Comment

I found this particularly helpful for sending code-page translated byte streams. Application uses old Code Page 437.
9

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)

Comments

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 «☺ 

Comments

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"

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.