Qt5 comes with a serial port initial use of the feeling is good.
Debug logging
. Pro File Added
QT += SerialPort
. h file Added
#include<QtSerialPort/QSerialPort>
#include<QtSerialPort/QSerialPortInfo>
Private slots: void My_readuart ();//serial port receive data slot function
Private:
Qserialport*my_serialport;
. cpp Files
Within the constructor
foreach (const qserialportinfo &info, Qserialportinfo::availableports ()) { & nbsp Qserialport serial; Serial.setport (info); if (Serial.open (QI Odevice::readwrite) { Ui->combobox->additem ( Info.portname ()); Ui->textedit->append (tr ("Port list detected:"); & nbsp Ui->textedit->append (Info.portname ()); ui-> Textedit->append (Info.description ()); Ui->textedit->append ( Info.manufacturer ()); serial.close (); } } my_serialport= New Qserialport (); ui->pushbutton_3->setenabled (false); Ui->combobox_2->setcurrentindex (1);//Default 9600
Open the Serial button slot function
void mainwindow::on_pushbutton_clicked () {// my_serialport= new Qserialport (); My_serialport->setportname (Ui->combobox->currenttext ()); My_serialport->open (qiodevice::readwrite); My_serialport->setbaudrate (Ui->combobox_2->currenttext (). ToInt ()); My_serialport->setdatabits (qserialport::D ata8); My_serialport->setparity (qserialport::noparity); My_serialport->setstopbits (qserialport::onestop); My_serialport->setflowcontrol (Qserialport::noflowcontrol); Connect (my_serialport,signal (Readyread ()), This,slot (My_readuart ())); Ui->pushbutton->setenabled (false);//Disable opening the serial port button ui->pushbutton_3->setenabled (TRUE);//Allow the serial port button to be closed}
Read the serial port slot function
void Mainwindow::my_readuart () { Qbytearray requestData; RequestData = My_serialport->readall (); if (requestdata!= NULL) { ui->textedit->append (tr (requestData)); } Requestdata.clear ();}
Send data slot function
void mainwindow::on_pushbutton_2_clicked () { my_serialport->write (Ui->lineedit->text (). ToLatin1 ());}
Turn off the serial port slot function
void mainwindow::on_pushbutton_3_clicked () { my_serialport->clear (); Ui->pushbutton->setenabled (true); Ui->pushbutton_3->setenabled (false); my_serialport->deletelater ();}
When testing with 9600 baud rate, data reception is very fast and does not require the QT4 to detect whether the receive buffer has any remaining data.
QT5 with serial debugging--use signal to receive data, automatically detect port list