티스토리 뷰

SWDesk

[Python] Serial 통신 예제

bizmaker 2023. 12. 14. 21:15

파이썬으로 UART 통신을 테스트하기 위한 소스 코

 

 

import serial
import tkinter as tk
from tkinter import ttk
import threading

class SerialInterface:
    def __init__(self, master):
        self.master = master
        self.ser = None
        self.is_connected = False

        self.port_var = tk.StringVar()
        self.baudrate_var = tk.StringVar()

        self.input_text = tk.StringVar()

        self.port_label = tk.Label(self.master, text="COM Port")
        self.port_entry = ttk.Combobox(self.master, textvariable=self.port_var, values=[f'COM{i}' for i in range(10)])
        
        self.baudrate_label = tk.Label(self.master, text="Baud Rate")
        self.baudrate_entry = ttk.Combobox(self.master, textvariable=self.baudrate_var, values=[9600, 14400, 19200, 38400, 57600, 115200])
        
        self.connect_button = tk.Button(self.master, text="Connect", command=self.connect)
        
        self.input_label = tk.Label(self.master, text="Input")
        self.input_entry = tk.Entry(self.master, textvariable=self.input_text)
        self.input_entry.bind('<Return>', self.send_data)  # input_entry에 엔터키 이벤트를 send_data 함수에 바인딩

        self.send_button = tk.Button(self.master, text="Send", command=self.send_data)
        
        self.output_label = tk.Label(self.master, text="Output")
        self.output_text = tk.Text(self.master, height=6, width=50)

        self.port_label.grid(row=0, column=0)
        self.port_entry.grid(row=0, column=1)
        self.baudrate_label.grid(row=1, column=0)
        self.baudrate_entry.grid(row=1, column=1)
        self.connect_button.grid(row=2, column=0, columnspan=2)
        self.input_label.grid(row=3, column=0)
        self.input_entry.grid(row=3, column=1)
        self.send_button.grid(row=4, column=0, columnspan=2)
        self.output_label.grid(row=5, column=0)
        self.output_text.grid(row=5, column=1)

    def connect(self):
        port = self.port_var.get()
        baudrate = int(self.baudrate_var.get())
        self.ser = serial.Serial(port, baudrate)
        self.is_connected = True
        thread = threading.Thread(target=self.receive_data, daemon=True)  # 수신을 위한 쓰레드 생성
        thread.start()  # 쓰레드 시작

    def receive_data(self):
        while self.is_connected:  # isConnected가 True일 동안
            data = self.ser.readline().decode('utf-8').strip()  # 데이터를 읽어옵니다.
            self.output_text.insert(tk.END, data + '')  # 출력창에 데이터 추가

    def send_data(self):
        data = self.input_text.get()
        if self.ser:
            self.ser.write(data.encode())

def main():
    root = tk.Tk()
    SerialInterface(root)
    root.mainloop()

if __name__ == "__main__":
    main()
반응형