[파이썬] PyQt 시리얼 포트 (`QSerialPort`)

PyQt is a powerful library that provides a wide range of tools and functionality for creating graphical user interfaces (GUIs) in Python. One of the many features PyQt offers is the QSerialPort class, which allows developers to easily communicate with serial devices such as Arduino boards or other microcontrollers.

In this blog post, we will explore how to use the QSerialPort class in PyQt to establish a serial connection, send and receive data, and handle serial events. Let’s dive in!

Prerequisites

Before we begin, make sure you have PyQt installed on your system. You can install it using pip:

pip install PyQt5

Establishing a Serial Connection

To establish a serial connection in PyQt, we first need to import the necessary classes:

from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo

To find available serial ports, we can use the QSerialPortInfo class:

serial_ports = QSerialPortInfo.availablePorts()

for port in serial_ports:
    print(port.portName())

Once we have identified the desired serial port, we can create an instance of QSerialPort:

serial = QSerialPort()

To open the serial port, specify the port settings such as the port name, baud rate, and parity:

serial.setPortName("COM1")
serial.setBaudRate(QSerialPort.Baud9600)
serial.setParity(QSerialPort.NoParity)

if serial.open(QSerialPort.ReadWrite):
    print("Serial port opened successfully!")

Sending and Receiving Data

To send data through the serial port, we can use the write() method:

data = b'Hello, Arduino!'
serial.write(data)

To receive data from the serial port, we can use the readyRead signal and read the available data:

def handle_ready_read():
    if serial.bytesAvailable():
        data = serial.readAll()
        print(data.decode())

serial.readyRead.connect(handle_ready_read)

Handling Serial Events

PyQt provides signals for various serial events such as data reception, errors, and readiness for reading or writing. You can connect event handlers to these signals to handle the corresponding events.

For example, to handle errors such as the serial port being disconnected:

def handle_error(error):
    print("Error:", error)

serial.errorOccurred.connect(handle_error)

Closing the Serial Connection

When you are done with the serial port, it’s important to properly close it:

serial.close()

Conclusion

Using the QSerialPort class in PyQt, we can easily establish a serial connection, send and receive data, and handle serial events. This functionality opens up a wide range of possibilities for integrating Python applications with serial devices.

I hope this blog post has provided you with a good introduction to working with serial ports in PyQt. Happy coding!