1. 程式人生 > >使用python pyserial模組串列埠通訊

使用python pyserial模組串列埠通訊

最近除錯通訊模組時,需要用UART串列埠輸入AT命令控制模組,手動輸入不便於自動化,所以就學習了下使用python進行串列埠控制。 serial模組安裝 pip install pyserial 常用的方法函式 匯入串列埠模組import serial;開啟串列埠ser = serial.Serial(埠名稱,...其他引數),ser.open()方法可以在close之後再次開啟相應埠;關閉串列埠ser.close();通過串列埠寫入ser.write(b''),引數需要使用位元組bytes型別,如果是str型別,則可以使用encode('utf-8')的方式進行轉換;讀取模組資訊的方法如下,x = ser.read()讀取一個位元組,x=read(n)讀取n個位元組,readline()可以用來讀取一行。 檢視COM口工具
python -m serial.tools.list_ports -v,可以列出所有串列埠名稱及屬性。 Serial引數說明 port埠名字,windows下為'COM1'等;baudrate (int)波特率,可以設定的範圍9600到115200;bytesize為每個位元組的位元數,設定值為FIVEBITS, SIXBITS,SEVENBITS, EIGHTBITS 5-8位元;parity設定校驗位PARITY_NONE, PARITY_EVEN,PARITY_ODD PARITY_MARK, PARITY_SPACE,用來設定校驗位;stopbits停止位,用來指示位元組完成,可以選擇的設定STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO;write_timeout(float) 寫入超時設定;timeout (float)讀出超時設定;xonxoff (bool)軟體流控開關;rtscts (bool)硬體RTS/CTS流控開關;dsrdtr (bool)硬體DSR/DTR流控開關。關於UART流控兩線方式沒有硬體流控,四線方式採用DSR、DTR進行流控,而RS232標準中可以有DSR、DTR的流控方式。RTS-request to send; CTS- clear to send;DSR-data set ready;DTR-Data Terminal Ready。 一個簡單示例
#!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()