PyCharm pyqt5 python串口通信封装类SerialCommunication
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                PyCharm pyqt5 python串口通信封装类SerialCommunication
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                
                            
                            
                            """
pyqt5串口通信文件SerialCommunication.py
"""
import binascii
import os
import serial
import serial.tools.list_ports
from PyQt5.QtGui import QPixmap# 全局變量,串口是否創建成功標志
Ret = False
# 串口列表串口號
port_list_number = []
# 串口列表名稱
port_list_name = []
# 獲取“串口指示燈亮”圖片文件路徑
imgLedOff = os.path.join(os.getcwd() + "\\images\\light_off.png")
# 獲取“串口指示燈滅”圖片文件路徑
imgLedOn = os.path.join(os.getcwd() + "\\images\\light_on.png")class Communication(object):"""Python串口通信封裝類"""# 初始化def __init__(self, com, bps, timeout):self.port = com  # 串口號self.bps = bps  # 波特率self.timeout = timeout  # 超時溢出self.main_engine = None  # 全局串口通信對象global RetRet = Falseself.data = Noneself.b_c_text = Nonetry:# 打開串口,并得到串口對象self.main_engine = serial.Serial(self.port, self.bps, timeout=self.timeout)# 判斷是否打開成功if self.main_engine.is_open:Ret = Trueexcept Exception as e:print("---異常---:", e)# 打印設備基本信息def Print_Name(self):"""打印設備基本信息"""print(self.main_engine.name)  # 設備名字print(self.main_engine.port)  # 讀或者寫端口print(self.main_engine.baudrate)  # 波特率print(self.main_engine.bytesize)  # 字節大小print(self.main_engine.parity)  # 校驗位print(self.main_engine.stopbits)  # 停止位print(self.main_engine.timeout)  # 讀超時設置print(self.main_engine.writeTimeout)  # 寫超時print(self.main_engine.xonxoff)  # 軟件流控print(self.main_engine.rtscts)  # 軟件流控print(self.main_engine.dsrdtr)  # 硬件流控print(self.main_engine.interCharTimeout)  # 字符間隔超時# 打開串口def Open_Engine(self):"""打開串口"""global Ret# 如果串口沒有打開,則打開串口if not self.main_engine.is_open:self.main_engine.open()Ret = True# 關閉串口def Close_Engine(self):"""關閉串口"""global Ret# print(self.main_engine.is_open)  # 檢驗串口是否打開# 判斷是否打開if self.main_engine.is_open:self.main_engine.close()  # 關閉串口Ret = False# 打印可用串口列表@staticmethoddef Print_Used_Com():"""打印可用串口列表"""port_list_name.clear()port_list_number.clear()port_list = list(serial.tools.list_ports.comports())if len(port_list) <= 0:print("The Serial port can't find!")else:for each_port in port_list:port_list_number.append(each_port[0])port_list_name.append(each_port[1])print(port_list_number)print(port_list_name)# 接收指定大小的數據# 從串口讀size個字節。如果指定超時,則可能在超時后返回較少的字節;如果沒有指定超時,則會一直等到收完指定的字節數。def Read_Size(self, size):"""接收指定大小的數據:param size::return:"""return self.main_engine.read(size=size)# 接收一行數據# 使用readline()時應該注意:打開串口時應該指定超時,否則如果串口沒有收到新行,則會一直等待。# 如果沒有超時,readline會報異常。def Read_Line(self):"""接收一行數據:return:"""return self.main_engine.readline()# 發數據def Send_data(self, data):"""發數據:param data:"""self.main_engine.write(data)# 更多示例# self.main_engine.write(bytes(listData))  # 發送列表數據listData = [0x01, 0x02, 0xFD]或listData = [1, 2, 253]# self.main_engine.write(chr(0x06).encode("utf-8"))  # 十六制發送一個數據# print(self.main_engine.read().hex())  #  # 十六進制的讀取讀一個字節# print(self.main_engine.read())#讀一個字節# print(self.main_engine.read(10).decode("gbk"))#讀十個字節# print(self.main_engine.readline().decode("gbk"))#讀一行# print(self.main_engine.readlines())#讀取多行,返回列表,必須匹配超時(timeout)使用# print(self.main_engine.in_waiting)#獲取輸入緩沖區的剩余字節數# print(self.main_engine.out_waiting)#獲取輸出緩沖區的字節數# print(self.main_engine.readall())#讀取全部字符。# 接收數據# 一個整型數據占兩個字節# 一個字符占一個字節def Receive_data(self, way):"""接收數據:param way:"""# 循環接收數據,此為死循環,可用線程實現print("開始接收數據:")bWaitRec = Truewhile bWaitRec:try:# 一個字節一個字節的接收if self.main_engine.in_waiting:if way == 0:for i in range(self.main_engine.in_waiting):print("接收ascii數據:" + str(self.Read_Size(1)))data1 = self.Read_Size(1).hex()  # 轉為十六進制data2 = int(data1, 16)  # 轉為十進制print("收到數據十六進制:"+data1+"  收到數據十進制:"+str(data2))if way == 1:# 整體接收# self.data = self.main_engine.read(self.main_engine.in_waiting).decode("utf-8")  # 方式一self.data = self.main_engine.read_all()  # 方式二print("接收ascii數據:", self.data)self.b_c_text = binascii.hexlify(self.data)  # 16進制Bytes轉Bytes,例:b'\x01\x06\xaa\x92\x12'轉b'0106aa9212'print("Bytes數據:", self.b_c_text)# 如果data不為空,則退出接收死循環if self.data.strip() != '':bWaitRec = Falseexcept Exception as e:print("異常報錯:", e)print("接收數據完畢!")
 
"""
pyqt5主對話框文件main.py
"""import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtGui import QPixmap
import SerialCommunication  # module SerialCommunication.py# myPyMainForm  # 主窗口對象
# labIndicator  # label控件對象class MyPyQTMainForm(QMainWindow, BitmapFontCreate.Ui_MainWindow):"""主界面"""def __init__(self):super(MyPyQTMainForm, self).__init__()self.setupUi(self)# 保存全局串口通信Communication對象self.myEngine = Noneself.strComNum = None  # 保存串口號def ComLedIndicator(self, comboIndex):"""串口狀態用LED指示燈指示。串口打開LED亮;串口關閉LED滅;"""if comboIndex >= 0:# 計算串口號COMxself.strComNum = SerialCommunication.port_list_number[comboIndex]# 創建串口通信對象myEngineself.myEngine = SerialCommunication.Communication(self.strComNum, 9600, 0.5)else:self.myEngine = Noneif SerialCommunication.Ret:# 利用label顯示圖片,串口指示燈亮icoLedOn = QPixmap(SerialCommunication.imgLedOn)myPyMainForm.labIndicator.setPixmap(icoLedOn)myPyMainForm.labIndicator.setScaledContents(True)else:# 利用label顯示圖片,串口指示燈滅icoLedOff = QPixmap(SerialCommunication.imgLedOff)myPyMainForm.labIndicator.setPixmap(icoLedOff)myPyMainForm.labIndicator.setScaledContents(True)def ComScan(self):"""串口掃描"""# 串口重新掃描前,首先關閉串口if self.myEngine:self.myEngine.Close_Engine()# 清空串口組合框myPyMainForm.comboComNum.clearEditText()myPyMainForm.comboComNum.clear()# 打印可用串口列表SerialCommunication.Communication.Print_Used_Com()# 向串口號組合框添加可用的串口號myPyMainForm.comboComNum.addItems(SerialCommunication.port_list_name)"""
主函數
"""
if __name__ == '__main__':app = QApplication(sys.argv)myPyMainForm = MyPyQTMainForm()# 禁止最大化按鈕myPyMainForm.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)# 禁止拉伸窗口大小myPyMainForm.setFixedSize(myPyMainForm.width(), myPyMainForm.height())# 清空串口號組合框myPyMainForm.comboComNum.clear()# 打印可用串口列表SerialCommunication.Communication.Print_Used_Com()# 向串口號組合框添加可用的串口號myPyMainForm.comboComNum.addItems(SerialCommunication.port_list_name)# 顯示主界面myPyMainForm.show()sys.exit(app.exec_()) 
                            
                        
                        
                        總結
以上是生活随笔為你收集整理的PyCharm pyqt5 python串口通信封装类SerialCommunication的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: SQL事务控制语言(TCL)
- 下一篇: 近百家公司高级运维的面试题汇总
