Why is my Python serial write command giving a TypeError?

I’m using Python 3.3 and pySerial for serial communication, but when I try to write a command to my COM port using the write() method, it doesn’t accept my string. I’m encountering the following error:

Error at ser.write("%01#RDD0010000107**\r") with Traceback like this:
data = to_bytes(data)
b.append(item)
TypeError: an integer is required.

Here’s the code I am using:

import time
import serial

ser = serial.Serial(
    port='\\\\.\\COM4',
    baudrate=115200,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS
)

if ser.isOpen():
    ser.close()
ser.open()
ser.isOpen()

ser.write("%01#RDD0010000107**\r")
out = ''
# Let's wait one second before reading output to give the device time to respond
time.sleep(1)

while ser.inWaiting() > 0:
    out += ser.read(40)

if out != '':
    print(">>" + out)

ser.close()

What could be the cause of the error, and how can I resolve it in the context of Python serial write?

From my experience with python serial write, I found that the problem was due to the string needing to be converted into a bytearray. To fix this, I modified my code like this:

ser.write("%01#RDD0010000107**\r".encode())

This change resolved the error and allowed me to send the string to the serial port correctly. Always remember to check the data type before sending it out!

Ah, yes, that’s one way to go about it. What I usually do is use bytes() to convert the string into a byte object before writing it. Here’s an example:

ser.write(bytes("%01#RDD0010000107**\r", 'utf-8'))

In fact, this method can be especially useful when you’re working with specific encodings like UTF-8. I’ve found it to be very reliable when dealing with python serial write issues, especially when the encoding matters.

Totally agree with both of you! Another approach I’ve found useful, especially when working with simpler encodings, is to explicitly use str.encode() with a specific encoding. For example:

ser.write("%01#RDD0010000107**\r".encode('ascii'))

This ensures that your data is encoded in the right format for the serial communication. It’s something I always do when troubleshooting python serial write errors. It’s also great for ensuring compatibility across different systems!