Sending ASCII Command Using PySerial

I am trying to send the following 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 get 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

I don’t know how I can solve this. close1 is just an example of the ASCII command I want to send, there is also status1 to see if my locks are open or closed, etc.

Thanks in advance

+4
source share
1 answer

- , Python 3 unicode, Python 2.x . PySerial bytes bytearray write. Python 2.x , Python 3.x Unicode , , , pySerial write.

pySerial Python 3, bytearray. , :

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

All Articles