Python's serial communication

Keywords: Python Windows Linux

Serial communication is a kind of communication mode between peripherals and computers, which transmits data bit by bit through data signal lines, ground lines, control lines, etc. This communication mode uses fewer data lines and can save communication cost in long distance communication, but its transmission speed is lower than that of parallel transmission. Serial port is a very general equipment communication protocol on computer. pyserial module encapsulates python's access to serial ports, providing a unified interface for the use of multiple platforms.

Installation:

pip3 install pyserial

Test:

Two CH340 (TTL transfer serial module) are connected to PC serial port and interact with each other through Python:

Simple serial port program implementation:

import serial #Import module
try:
  #Port, GNU / Linux Upper/ dev / ttyUSB0 Wait or Windows Upper COM3 etc.
  portx="COM3"
  #Baud rate, one of the standard values: 50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
  bps=115200
  #time-out,None: Always wait for the operation, 0 to return the request result immediately, and the other values are waiting time-out.(In seconds)
  timex=5
  # Open the serial port and get the serial object
  ser=serial.Serial(portx,bps,timeout=timex)

  # Writing data
  result=ser.write("I'm Dong Xiaodong.".encode("gbk"))
  print("Write total bytes:",result)

  ser.close()#Close serial port

except Exception as e:
    print("---abnormal---: ",e)

 

 

Get a list of available serial ports:

import serial #Import module

import serial.tools.list_ports
port_list = list(serial.tools.list_ports.comports())
print(port_list)
if len(port_list) == 0:
   print('No Available Serial Port')
else:
    for i in range(0,len(port_list)):
        print(port_list[i])

 

Hexadecimal processing:

import serial #Import module
try:
  portx="COM3"
  bps=115200
  #time-out,None: Always wait for the operation, 0 to return the request result immediately, and the other values are waiting time-out.(In seconds)
  timex=None
  ser=serial.Serial(portx,bps,timeout=timex)
  print("Serial details parameters:", ser)

  #Hexadecimal transmission
  result=ser.write(chr(0x06).encode("utf-8"))#Writing data
  print("Write total bytes:",result)

  #Hexadecimal Reading
  print(ser.read().hex())#Read a byte

  print("---------------")
  ser.close()#Close serial port

except Exception as e:
    print("---abnormal---: ",e)

 

Additional details:

import serial #Import module
try:

  #Port, GNU / Linux Upper/ dev / ttyUSB0 Wait or Windows Upper COM3 etc.
  portx="COM3"
  #Baud rate, one of the standard values: 50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
  bps=115200
  #time-out,None: Always wait for the operation, 0 to return the request result immediately, and the other values are waiting time-out.(In seconds)
  timex=5
  # Open the serial port and get the serial object
  ser=serial.Serial(portx,bps,timeout=timex)
  print("Serial details parameters:", ser)



  print(ser.port)#Get the current open serial name
  print(ser.baudrate)#Obtaining baud rate

  result=ser.write("I'm Dong Xiaodong.".encode("gbk"))#Writing data
  print("Write total bytes:",result)


  #print(ser.read())#Read a byte
  # print(ser.read(10).decode("gbk"))#Read ten bytes
  #print(ser.readline().decode("gbk"))#Read a row
  #print(ser.readlines())#Read multiple rows, return list, must match timeout
  #print(ser.in_waiting)#Get the number of bytes remaining in the input buffer
  #print(ser.out_waiting)#Get the number of bytes in the output buffer

  #Loop receives data, which is a dead loop and can be implemented by threads
  while True:
         if ser.in_waiting:
             str=ser.read(ser.in_waiting ).decode("gbk")
             if(str=="exit"):#Exit sign
                 break
             else:
               print("Data received:",str)

  print("---------------")
  ser.close()#Close serial port


except Exception as e:
    print("---abnormal---: ",e)

 

Partial packaging:

The encapsulation method of reading data is not very useful, and it has to be received circularly, which makes it more complicated.

import serial #Import module
import threading
STRGLO="" #Read data
BOOL=True  #Read flag bit

#Realization of Reading Code Ontology
def ReadData(ser):
    global STRGLO,BOOL
    # Loop receives data, which is a dead loop and can be implemented by threads
    while BOOL:
        if ser.in_waiting:
            STRGLO = ser.read(ser.in_waiting).decode("gbk")
            print(STRGLO)


#Open serial port
# Port, GNU / Linux Upper/ dev / ttyUSB0 Wait or Windows Upper COM3 etc.
# Baud rate, one of the standard values: 50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
# time-out,None: Always wait for the operation, 0 to return the request result immediately, and the other values are waiting time-out.(In seconds)
def DOpenPort(portx,bps,timeout):
    ret=False
    try:
        # Open the serial port and get the serial object
        ser = serial.Serial(portx, bps, timeout=timeout)
        #Determine whether the opening is successful
        if(ser.is_open):
           ret=True
           threading.Thread(target=ReadData, args=(ser,)).start()
    except Exception as e:
        print("---abnormal---: ", e)
    return ser,ret



#Close serial port
def DColsePort(ser):
    global BOOL
    BOOL=False
    ser.close()



#Writing data
def DWritePort(ser,text):
    result = ser.write(text.encode("gbk"))  # Writing data
    return result




#Read data
def DReadPort():
    global STRGLO
    str=STRGLO
    STRGLO=""#Clear out the current read
    return str



if __name__=="__main__":
    ser,ret=DOpenPort("COM6",115200,None)
    if(ret==True):#Determine whether the serial port is successfully opened
         count=DWritePort(ser,"I'm Dong Xiaodong, Haha.")
         print("Number of bytes written:",count)
         #DReadPort() #ReadComm
         #DColsePort(ser)  #Close serial port

Posted by xpherism on Wed, 10 Apr 2019 20:06:31 -0700