The implementation process of serialport serial port class is as follows:
First: we need to add a sentence QT += serialport to the project file pro file
Then add #include <QtSerialPort/QSerialPort> in the header file
#include <QtSerialPort/QSerialPortInfo>
Second: Configure the serial port parameter function. What I wrote here is 8-bit data, no parity, one stop bit, 9600 baud rate, and these configurations can be changed according to your own needs.
intMainWindow::open(QStringcomPort)
{
this->com = comPort;
// serial port parameter settings
serial = new QSerialPort ();
serial ->setPortName( com ); //Set the serial port name
if(!serial->open(QIODevice::ReadWrite))
{
qDebug("openserialerror!");
return -1;
}
else
{
qDebug("openserialok");
}
serial ->setBaudRate( QSerialPort :: Baud9600 ); //9600 baud rate
serial ->setDataBits( QSerialPort :: Data8 ); //8 data bits
serial ->setParity( QSerialPort :: EvenParity ); //check
serial ->setStopBits( QSerialPort :: OneStop ); //1 stop bit
serial->setFlowControl(QSerialPort::NoFlowControl);
return0;
}
Third: write data only one line can write data
serial ->write( ) This write prototype is like this write( const char *data, qint64 len);
Fourth: read data
QByteArraybuf=serial->readAll();
Fifth: close the serial port
serial->close();
The above serial I defined in the header file is QSerialport *serial.
The serialport class in QT is very easy to use. It is ok to configure the read, write and close of the serial port. Code address https://download.csdn.net/download/weixin_39770778/10326200