---
# System prepended metadata

title: 應用 1 - 顯示串列埠接收的資料
tags: [python, tutorials, pyqt]

---

# 應用 1 - 顯示串列埠接收的資料

###### tags: `python` `pyqt` `tutorials`

1. 利用 QThread 創建一個專門處理 serial 的物件，叫做 SerialHandler
2. 當接收到資料時， SerialHandler 發送訊號


範例可以參考[pyqt-example](https://gitlab.com/MVMC-lab/pyqt-example)中的exp02，或下面範例


``` python
from PyQt5.QtCore import QObject
from PyQt5.QtCore import pyqtSlot, QThread, pyqtSignal, QObject
import time
import serial
import serial.tools.list_ports

class SerialHandler(QThread):
    signal_serialdata = pyqtSignal(str)
    def __init__(self):
        super(SerialHandler, self).__init__()
        self.com = serial.Serial()
        self.com.port = 'COM1'
        self.com.open()
    # override run function
    def run(self):
        while True:
            time.sleep(1)
            if self.com.in_waiting:
                buf = self.com.read(self.com.in_waiting)
                string = str(buf)
                self.signal_serialdata.emit(string)
                self.com.write(buf)
                print(f'{string}')
            else:
                print('Nothing in Buffer')
    
    def __del__(self):
        if self.com.is_open:
            self.com.close()
            print('Close Port ['+self.com.port+']')

class cli_print(QThread):
    def __init__(self):
        super(cli_print, self).__init__()

if __name__ == "__main__":
    COM = SerialHandler()
    COM.start()
    COM.wait()
```