Sending ASCII Command using PySerial

Jon220 picture Jon220 · Jul 2, 2015 · Viewed 21.8k times · Source

I am trying to send the followings ASCII command: close1

using PySerial, below is my attempt:

import serial

#Using  pyserial Library to establish connection
#Global Variables
ser = 0

#Initialize Serial Port
def serial_connection():
    COMPORT = 3
    global ser
    ser = serial.Serial()
    ser.baudrate = 38400 
    ser.port = COMPORT - 1 #counter for port name starts at 0




    #check to see if port is open or closed
    if (ser.isOpen() == False):
        print ('The Port %d is Open '%COMPORT + ser.portstr)
          #timeout in seconds
        ser.timeout = 10
        ser.open()

    else:
        print ('The Port %d is closed' %COMPORT)


#call the serial_connection() function
serial_connection()
ser.write('open1\r\n')

but as a result I am receiving the following error:

Traceback (most recent call last):
      , line 31, in <module>
        ser.write('open1\r\n')
      , line 283, in write
        data = to_bytes(data)
      File "C:\Python34\lib\site-packages\serial\serialutil.py", line 76, in to_bytes
        b.append(item)  # this one handles int and str for our emulation and ints for Python 3.x
    TypeError: an integer is required

Not sure how I would be able to resolve that. close1 is just an example of an ASCII command I want to send there is also status1 to see if my locks are open or close, etc.

Thanks in advance

Answer

shuttle87 picture shuttle87 · Jul 2, 2015

This issue arises because Python 3 stores its strings internally as unicode but Python 2.x does not. PySerial is expecting to get a bytes or bytearray as a parameter to write. In Python 2.x the string type would be fine for this but in Python 3.x the string type is Unicode and hence not compatible with what pySerial write needs.

In order to use pySerial with Python 3 you need to use a bytearray. So your code would look need to look like this instead:

ser.write(b'open1\r\n')