25

Using Python 3.3 and pySerial for serial communications.

I'm trying to write a command to my COM PORT but the write method won't take my string. (Most of the code is from here Full examples of using pySerial package

What's going on?

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 (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
    out += ser.read(40)

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


ser.close()

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

Community
  • 1
  • 1
Garvin
  • 815
  • 2
  • 10
  • 16
  • 4
    Probably because serial expects a bytearray and not a string in python3. Perhaps the following can help you: http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3 – Dov Grobgeld Mar 08 '14 at 21:10
  • adding .encode() after my string fixed my problem! (I also stripped some of the unnecessary parts out). Thanks! – Garvin Mar 08 '14 at 21:24
  • @Garvin If the problem is solved, could you please write an answer yourself and mark the question as answered? Thanks! – Fookatchu Mar 10 '14 at 09:38

3 Answers3

39

It turns out that the string needed to be turned into a bytearray and to do this I editted the code to

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

This solved the problem

Garvin
  • 815
  • 2
  • 10
  • 16
10

You have found the root cause. Alternately do like this:

ser.write(bytes(b'your_commands'))
Murphy Meng
  • 207
  • 3
  • 6
1

I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.

I'm omitting the com port settings here:

>>>import serial

>>>ser = serial.Serial(5)

>>>ser.close()

>>>ser.open()

>>>ser.write("1".encode())

1

>>>
Steph Sharp
  • 10,659
  • 4
  • 42
  • 79