Based on pyserial [Python serial communication]

Preface

Python serial communication has many ways, this paper is based on pyserial.First install the pyserial dependency library, understand the commonly used method functions, and understand the description of Serial parameters; then the computer looks at the available ports, for a simple example: can automatically detect and connect the serial port, collect data of the serial port; and finally see the results of the operation.

Install pyserial

pip install pyserial

View available ports

# coding:utf-8
import serial.tools.list_ports
plist = list(serial.tools.list_ports.comports())

if len(plist) <= 0:
    print("No port found!")
else:
    plist_0 = list(plist[0])
    serialName = plist_0[0]
    serialFd = serial.Serial(serialName, 9600, timeout=60)
    print("Available Port Names>>>", serialFd.name)

Run result:

Note: When running in pyCharm environment, there is a collected sensor on the serial port of the computer (connected to the computer through the serial port)

Common method functions

  • Import serial module import serial;
  • Open Serial Ser =Serial.Serial(port name,... Other parameters),
  • ser.open() The method can open the corresponding port again after close;
  • Close Serial PortSer.close();
  • Write through serial portSer.write(b''), parameter needs bytes bytes type, if str type, can be converted using encode('utf-8'); read module information as follows:
    -> x=Ser.read() Reads a byte, x=read(n) reads n bytes, and readline() can be used to read a line.

View COM Oral Work

Python-mSerial.tools.list_Ports-v, which lists all serial port names and properties.

Serial parameter description

Port port name,'COM1'etc. under windows;

baudrate (int) baud rate, which can range from 9600 to 115200;

bytesize is the number of bits per byte, set to FIVEBITS, SIXBITS,SEVENBITS, EIGHTBITS 5-8 bits;

parity setting check bit PARITY_NONE, PARITY_EVEN,PARITY_ODD PARITY_MARK,PARITY_SPACE, used to set check bits; stopbits, used to indicate byte completion, optionally set STOPBITS_ONE,STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO; write_timeout(float) write timeout setting;

timeout (float) readout timeout setting; xonxoff (bool) software flow control switch;

rtscts (bool) hardware RTS/CTS flow control switch;

dsrdtr (bool) hardware DSR/DTR flow control switch.

There is no hardware flow control for UART two-wire flow control. DSR and DTR are used for four-wire flow control. DSR and DTR can be used for flow control in RS232 standard.RTS-request to send; CTS-clear to send; DSR-data set ready; DTR-Data Terminal Ready.

A simple example: can automatically detect and connect the serial port, collect data from the serial port

#!usr/bin/python3.6

import serial
import sys
import os
import time
import re

global MAX_LOOP_NUM
global newCmd
MAX_LOOP_NUM = 10
 
def waitForCmdOKRsp():
    maxloopNum = 0
    while True:
        line = ser.readline()
        maxloopNum = maxloopNum + 1
        

        try:
            print("Rsponse : %s"%line.decode('utf-8'))
        except:
            pass
       

        if ( re.search(b'OK',line)):
            break

        elif(maxloopNum > MAX_LOOP_NUM):
            sys.exit(0)


def sendAT_Cmd(serInstance,atCmdStr,waitforOk):
    print("Command: %s"%atCmdStr)
    serInstance.write(atCmdStr.encode('utf-8'))
    #or define b'string',bytes should be used not str
    if(waitforOk == 1):
        waitForCmdOKRsp()
    else:
        waitForCmdRsp()

ser = serial.Serial("COM5",9600,timeout=30)
sendAT_Cmd(ser,'AT+CFUN=1\r',1)
ser.close()

Combining the above two codes, the serial port can be automatically detected and connected to collect data from the serial port

# !usr/bin/python3.6

import serial
import sys
import os
import time
import re

import serial.tools.list_ports

global MAX_LOOP_NUM
global newCmd

MAX_LOOP_NUM = 10


def waitForCmdOKRsp():
    maxloopNum = 0

    while True:

        line = ser.readline()                              #Read a row of data
        maxloopNum = maxloopNum + 1                        #Calculate Read Length

        try:
            print("Rsponse : %s" % line.decode('utf-8'))  #Serial port receives data and displays it
        except:
            pass

        if (re.search(b'OK', line)):
            break
        elif (maxloopNum > MAX_LOOP_NUM):
            sys.exit(0)


def sendAT_Cmd(serInstance, atCmdStr, waitforOk):
   # print("Command: %s" % atCmdStr)
    serInstance.write(atCmdStr.encode('utf-8'))   # atCmdStr baud rate
    # or define b'string',bytes should be used not str

    if (waitforOk == 1):
        waitForCmdOKRsp()
    else:
        waitForCmdRsp()


plist = list(serial.tools.list_ports.comports())

if len(plist) <= 0:
    print("No port found!")
else:
    plist_0 = list(plist[0])
    serialName = plist_0[0]       #Automatically detect the serial port first, detect the available serial port, take out the serial name

#ser = serial.Serial("COM6", 115200, timeout=30)
ser = serial.Serial(serialName, 115200, timeout=30)  # timeout=30 30s
print("Available Port Names>>>", ser.name)
sendAT_Cmd(ser, 'AT+CFUN=1\r', 1)
ser.close()

Operation effect:

I used CC2530 (Zigbee) to collect temperature and humidity data, through the serial port and computer connection, after running this program, the serial port can be automatically detected, then CC2530 data can be obtained, and then displayed on the computer side.

Hope it helps you.

Tags: Python pip Pycharm Windows

Posted on Tue, 19 May 2020 19:37:42 -0700 by gevo12321