[python] Make a serial port tool (Part 2)!

      In the previous chapter, we talked about the design of the UI interface. In this section, we will talk about how to implement its functions.

1. Example demonstration

1. Create a .py file. The following code is used to obtain all serial port information:

import serial
import serial.tools.list_ports

from PyQt5.QtWidgets import QComboBox

class My_ComBoBox(QComboBox):

    def __init__(self, parent = None):
        super(My_ComBoBox,self).__init__(parent)

    
    def showPopup(self):
        # 先清空原有的选项
        self.clear()
        index = 1

        # 获取接入的所有串口信息,插入combobox的选项中
        port_list = self.get_port_list(self)
        if port_list is not None:
            for i in port_list:
                self.insertItem(index, i)
                index += 1
        QComboBox.showPopup(self)# 弹出选项框

    @staticmethod
    # 获取接入的COM
    def get_port_list(self):
        try:
            port_list = list(serial.tools.list_ports.comports())
            for port in port_list:
                yield str(port)
        except Exception as err:
            print("获取接入的串口设备出错!错误信息为:" + str(err))

Then add the following code under our UI interface code:

Then let’s take a look at opening our main file and running it:

 Click to display all serial port information obtained as shown above.

2. Open the serial port:

 The previous function has helped us obtain the information of all serial ports. Now let's implement the function of opening the serial port.

(1) In order for everyone to understand, here is a step-by-step explanation. All serial port information has been obtained previously. The first line of code uses the re.split() function of the re module, which is mainly used to extract port number information. The parameters in the second line of code are port number, baud rate, and timeout.

comport_ = re.split(r'([,:` -])',ui.comboBox.currentText())

ser = serial.Serial(comport_[0],ui.comboBox_3.currentText(),timeout=self.timex)

(2) Add pop-up information

msg_box = QMessageBox(QMessageBox.Warning, '完成', '串口已打开!')
msg_box.exec_()

(3) The code to open the serial port is as follows:

def Open_serial(self):

    global ser

    try:

        serrial_one = 0

        if serrial_one == 0:

            comport_ = re.split(r'([,:` -])',ui.comboBox.currentText())

            ser = serial.Serial(comport_[0],ui.comboBox_3.currentText(),timeout=self.timex)
            time.sleep(0.1)
            ser.isOpen()
            ser.flushInput()

            msg_box = QMessageBox(QMessageBox.Warning, '完成', '串口已打开!')
            msg_box.exec_()


    except (IndexError,ValueError,TypeError,NameError) as e:
        print(e)

Run as follows:

3. Close the serial port:

How to close the serial port, just close it directly.

def close_serial(self):
        ser.close()
        msg_box = QMessageBox(QMessageBox.Warning, '完成', '串口已关闭!')
        msg_box.exec_()

Run as follows:

4.ASCII type sending data and receiving data:

def write_serial(self):
        if ui.radioButton.isChecked() == True:

            ser.write(b' %s\n'%(ui.lineEdit.text().encode('ascii')))
            Read = ser.readlines()   ###读多行数据
    
            
            ser.flushInput()
            
            # time.sleep(2)
            ui.textBrowser.append(str(Read))
            # ser.flushInput()
            QApplication.processEvents()

Run as follows:

(1) Select first

(2) Enter the data to be sent in the text box, and textBrowser receives the returned data.

 

The data sent by hex is similar to the above, so I won’t give an example.

5.Button function: 

def button(self):
        ui.pushButton_2.clicked.connect(self.Open_serial)##按钮1

2. Summary

The basic serial port sending and receiving data is as mentioned above. I will write it here today.

@Neng

Guess you like

Origin blog.csdn.net/pengneng123/article/details/131662743