Qt study notes (2) - add serial port program and debugging

1 Overall layout of the serial debugger

insert image description here
Qt version greater than 5.1.

1.1 Add serialport in the pro file

QT += serialport

insert image description here

1.2 Add the library file in the .h file

#include <QtSerialPort>

insert image description here

1.3 Add an instance

QSerialPortThe instance added under private in the .h header file mSerialPort.
insert image description here

1.4 Add serial port to send test code

Add test code in the startup function to verify whether data can be sent out.

monitor::monitor(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::monitor)
{
    ui->setupUi(this);
    // 测试代码
	mSerialPort.setPortName("COM1");
    mSerialPort.setBaudRate(QSerialPort::Baud115200);
    mSerialPort.setParity(QSerialPort::NoParity);
    mSerialPort.setDataBits(QSerialPort::Data8);
    mSerialPort.setStopBits(QSerialPort::OneStop);
    mSerialPort.open(QSerialPort::ReadWrite);
    if(mSerialPort.isOpen()){
        qDebug() << "Serial Port is Opened Successfully.";
        mSerialPort.write("hello world");
    }else{
        qDebug() << "Serial Port is not Opened.串口打开失败。";
    }
}

2. It is recommended to download a virtual serial port driver (Virtual Serial Port Driver), set the connection between COM1 and COM2, connect the program to COM1, and connect the serial debugging assistant to COM2.
insert image description here
3. Run the program and view the serial port debugging assistant:
insert image description here

Shortcut key for function creation:
After declaring the function in the .h file, press alt+Enter, and then press Enter to quickly create the definition of the corresponding function in .cpp.

Guess you like

Origin blog.csdn.net/qq_45362336/article/details/130647162