Sending ASCII Command using PySerial

28,092

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')
Share:
28,092
Jon220
Author by

Jon220

Updated on July 03, 2020

Comments

  • Jon220
    Jon220 almost 4 years

    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

  • Jon220
    Jon220 almost 9 years
    thank you that worked well. one additional question if you don't mind 1) how would i be able to print out the result of what is received such as if i type status1 it should return close1/open1 and the other question which is a bit more simple is if (ser.isOpen() == False): does not exactly check to see if the port is open as even when nothing is connected it bypasses that line and tryies to send a command which obviously returns an error thanks
  • shuttle87
    shuttle87 almost 9 years
    @Jon220, I suggest you have a go at this and ask in a new question if you get stuck.