Qt (6)--Qt5.5.1 implements Universal serial Port program

Source: Internet
Author: User
Tags sendmsg



Recently, the department is doing high-speed camera, through the image capture card and its own high-speed camera link, so as to capture and collect images. Image capture card and high-speed camera is through the Cameralink connection, which also contains the camera and image capture card between the serial port hardware excuse, in the teacher's request, the realization of two serial port programs, one is through the Cameralink API to achieve serial data transmission, One is through the USB to RS422 adapter, to achieve the high-speed camera registers read and write. This article mainly introduces the Qserialport and qserialportinfo two classes through QT, the realization of the serial port program.



The development environment used in this paper is vs2010+qt5.5.1 version, all programs are not compiled by QT Creator, if necessary can introduce VS2010 and QT environment and simple use.


    • Qserialport


Qserialport This class is introduced from the QT5.1, before all through the qiodevice themselves to define the serial port class, thus realizing the development of the serial port program. Now introduced this class, will be very convenient to develop the serial port program. To use this class, you need to include the path to the include in the project catalog and additional dependencies, along with the path to the link library, and the name of the link library:





    • Project---> Properties---> C + +---> General--->c:\qt\qt5.5.1\5.5\msvc2010\include\qtserialport
    • Project---> Properties---> Input + +---> Additional dependencies--->qt5serialport.lib (in the case of the debug version, the Qt5SerialPortd.lib) version
    • The source file or header file needs to be added to #include<qserialport>
Serial port information can be obtained through the Qserialportinfo class, through this class, you can correctly determine the serial port you want to open, at the same time can obtain the serial port descriptive information and manufacturers information. The serial port has three kinds of open mode, namely Readonly,writeonly, and ReadWrite. At the same time, it can set its stop bit, baud rate, data bits, check mode and flow control, corresponding functions are as follows: Setstopbits (), Setbaudrates (), Setdatabits (), setparity (), and Setflowcontrol ()。





The serial data is written via WriteData (const char * data, Qint64 maxSize) and write (const char * data, Qint64 maxSize), which is a protected attribute and can only be accessed in subclasses , while the latter is the public property. When the serial port is open and has a writable property, you can write data through the Write function.



The serial port data is read through readdata (char * data, Qint64 maxSize), read (Qint64 maxSize), if you need to read all the data at once, you can pass the ReadAll () Read all the data in the serial buffer.



The buffer size inside the serial port can be achieved by: Setreadbuffersize (qint64 size). When the buffer size is set, the serial port can only receive a size data stream, so there is the possibility of data loss. When set to 0, it does not mean that the buffer size is 0, but infinity, so that you can save all the data received intact. This is the default property for the buffer size.



Whether there is a new data read-in buffer is determined by the readready () signal. This is a time-driven way to determine if there is data that can be read in. There is also Waitforreadyread () to wait for the polling whether there is data to reach the serial port, but this is a blocking read, the personal feel is not too good, so when writing the serial port is the event-driven way to determine that there is enough data can be read into.


    • Qserialportinfo


Use the static functions to generate a list of Qserialportinfo objects. Each Qserialportinfo object in the list represents a single serial port and can is queried for the port name, System Locat Ion, description, and manufacturer. The Qserialportinfo class can also be used as a input parameter for the Setport () method of the Qserialport class.



The functions that may be used more are description (), Manufacturer (), and SerialNumber (). Thus obtaining descriptive information, such as a communication port. USB to the serial port and other description of the serial port information, serial port manufacturer information and serial name, on the computer performance as com~.


    • How to get all the serial ports on your computer



void CameraSerialPort::getSerialPortID()
{
	 serialInfo=new QSerialPortInfo();
	 serialList=serialInfo->availablePorts();
	int nSerialnum=serialList.length();
	for(int i=0;i<nSerialnum;i++)
	{
		QString serialName=serialList[i].portName();
		QString serialDesp=serialList[i].description();
		serialPortAssitant.serialPortcomboBox->addItem(serialName);
	}
	
	QString currentPort=serialPortAssitant.serialPortcomboBox->currentText();
	portToOpen=currentPort;
	QString  portStatus=currentPort+" closed";
	serialPortAssitant.status->statusInfo->setText(portStatus.toUpper());
	QPalette font_palette;
	font_palette.setColor(QPalette::WindowText,Qt::red);
	serialPortAssitant.status->statusInfo->setPalette(font_palette);
}
Because directly from their own project files copied from the source, here a little bit about the properties:





1, the definition of the variable, in the header file, here is not posted, the interception is defined as follows:




QSerialPortInfo* serialInfo;
	QList<QSerialPortInfo>serialList;
2, Qlist<qserialportinfo>availableports () returns a list of Qserialportinfo, stored in the data structure qlist.





3, Serialportcombox is a qcombobox, drop-down list.



4, the last few lines are used to display the status of the serial port information, to achieve the effect







    • Open serial port and write data via serial port


After the serial port information is obtained, the port can be selected to open and read and write data. Post the code and then analyze it for analysis:




void CameraSerialPort :: Write ()
{
<span style = "background-color: rgb (255, 204, 51);"> QString sendMsg = serialPortAssitant.sendLine-> text (); </ span>
<span style = "background-color: rgb (255, 204, 0);"> QByteArray temp = sendMsg.toLatin1 (); </ span>
if (IsSendByHex)
{
temp = HexStrToByteArray (sendMsg);
}
<span style = "background-color: rgb (255, 204, 0);"> char * sendContent = temp.data (); </ span>
<span style = "background-color: rgb (255, 204, 0);"> qint64 sendedNum = serialPort-> write (sendContent, temp.count ()) </ span>;

// --------------- Judgment whether to send data successfully ---------------------- //
if (sendedNum ==-1)
{
errorValue = serialPort-> error ();
if (IsShowCurrentTime)
{
errorInfo = "";
currentTime = QDateTime :: currentDateTime ();
timeinfo = currentTime.toString ("yyyy__MM__d__hh: mm: ss");
errorInfo = QString :: fromLocal8Bit ("Error message");
errorInfo + = timeinfo;
errorInfo + = "\ n";
}
else
{
errorInfo = "";
errorInfo = QString :: fromLocal8Bit ("Error message");
errorInfo + = "\ n";
}
serialPortAssitant.ReciveWidget-> append (errorInfo + getValueContent (errorValue));
return;
}
// ------------- Show sending data ----------------------- //

// The size of temp is based on whether it is sent in hexadecimal
sendCount + = temp.count ();
serialPortAssitant.status-> TxByte-> setText (QString :: number (sendCount));
QString showSendMsg;
if (IsShowSendMsg)
{
if (IsShowCurrentTime)
{

currentTime = QDateTime :: currentDateTime ();
timeinfo = currentTime.toString ("yyyy__MM__d__hh: mm: ss");
showSendMsg + = QString :: fromLocal8Bit ("Send data:");
showSendMsg + = timeinfo;
showSendMsg + = "\ n";
// Determine whether to display hexadecimal or ACSII characters
if (IsSendByHex)
showSendMsg + = ByteArrayToHexStr (temp);
else
showSendMsg + = temp;
}
else
{
showSendMsg = QString :: fromLocal8Bit ("Send data:");
if (IsSendByHex)
showSendMsg + = ByteArrayToHexStr (temp);
else
showSendMsg + = temp;
Ranch
}
serialPortAssitant.ReciveWidget-> append (showSendMsg);

}
IsWrittenSuccessed = true;
}

void CameraSerialPort :: sendData ()
{
if (! IsSerialPortOpen)
{
if (serialPort! = NULL)
{
serialPort-> close ();
}
<span style = "background-color: rgb (255, 204, 0);"> serialPort = new QSerialPort (portToOpen); </ span>
if (serialPort == NULL)
{
errorValue = serialPort-> error ();
QString errorContent = getValueContent (errorValue);
if (IsShowCurrentTime)
{
errorInfo = "";
currentTime = QDateTime :: currentDateTime ();
timeinfo = currentTime.toString ("yyyy__MM__d__hh: mm: ss");
errorInfo = QString :: fromLocal8Bit ("Error message");
errorInfo + = timeinfo;
errorInfo + = "\ n";
}
else
{
errorInfo = "";
errorInfo = QString :: fromLocal8Bit ("Error message");
errorInfo + = "\ n";
}
serialPortAssitant.ReciveWidget-> append (errorInfo + errorContent + QString :: fromLocal8Bit (", please select the correct port again \ n"));
return;
}

<span style = "background-color: rgb (255, 204, 0);"> if (! serialPort-> open (QIODevice :: ReadWrite)) </ span>
{
errorValue = serialPort-> error ();
QString errorContent = getValueContent (errorValue);
if (IsShowCurrentTime)
{
errorInfo = "";
currentTime = QDateTime :: currentDateTime ();
timeinfo = currentTime.toString ("yyyy__MM__d__hh: mm: ss");
errorInfo = QString :: fromLocal8Bit ("Error message");
errorInfo + = timeinfo;
errorInfo + = "\ n";
}
else
{
errorInfo = "";
errorInfo = QString :: fromLocal8Bit ("Error message");
errorInfo + = "\ n";
}
serialPortAssitant.ReciveWidget-> append (errorInfo + errorContent);
return;
}
<span style = "background-color: rgb (255, 0, 0);"> connect (serialPort, SIGNAL (readyRead ()), this, SLOT (onReadyRead ())); </ span>
serialPort-> setDataBits (QSerialPort :: Data8);
serialPort-> setStopBits (QSerialPort :: OneStop);
serialPort-> setParity (QSerialPort :: NoParity);
serialPort-> setFlowControl (QSerialPort :: NoFlowControl);

QString serialStatusInfo;
serialStatusInfo = serialPortAssitant.serialPortcomboBox-> currentText (). toUpper ();
serialStatusInfo + = "OPENED";
serialStatusInfo + = ",";
serialStatusInfo + = QString :: number (serialPort-> baudRate ());
serialStatusInfo + = ",";
serialStatusInfo + = serialPortAssitant.DataWidthcomboBox-> currentText ();
serialStatusInfo + = ",";
serialStatusInfo + = serialPortAssitant.ParityWidthcomboBox-> currentText (). toUpper ();
serialStatusInfo + = ",";
serialStatusInfo + = serialPortAssitant.StopWidthcomboBox-> currentText ();
serialStatusInfo + = ",";
serialStatusInfo + = serialPortAssitant.FLowControlcomboBox-> currentText (). toUpper ();
QPalette font_palette;
font_palette.setColor (QPalette :: WindowText, Qt :: darkCyan);
serialPortAssitant.status-> statusInfo-> setText (serialStatusInfo);
serialPortAssitant.status-> statusInfo-> setPalette (font_palette);

serialPortAssitant.sendBtn-> setText (QString :: fromLocal8Bit ("Send"));
IsSerialPortOpen = true;
}

else
{
if (IsRepeatSend)
{
repeatSend-> start ();
}
Write ();
}
}





First look at the Write function: Here are a few lines of key code drawn from the Write function:





QString sendMsg=serialPortAssitant.sendLine->text();
<span style="white-space:pre">	</span>QByteArray temp=sendMsg.toLatin1();
	char *sendContent=temp.data();
	qint64 sendedNum=serialPort->write(sendContent,temp.count());
1, the first line is from the Qlineedit to obtain the data needed to send information;





2, the second line to the third line of code is the data type that needs to convert qstring to char *.



3, the fourth line is through the Qiodevice class member function write write data.



4, the remainder is some of the details of the error display and display information, and it is very important to send data in ASCII format or 16 binary data.



Next is the SendData () function.






1, the first line is instantiated by Porttoopen Qserialport, the constructor is: qserialport (const QString & name, Qobject * parent = Q_nullptr )



2, the second line is to open the serial port, open mode is ReadWrite, can be written and readable



3, the third line is through the readread () signal to realize the serial port data readout, event-driven way. This line I added red in the source code, the reason is, must be opened after the serial port, the implementation of the Readyread () signal and corresponding slot function connection, if the serial port is not initialized successfully, then the signal can be started. I started in cameraserialport this class of initialization in the definition of this signal slot link, has not read the serial data, the results in the online search for a half-day reason, also did not find this problem. Think about it, and then move the code here, it's ready.



The results of opening the serial port and sending the data










    • Serial port to receive data



void CameraSerialPort :: Read ()
{
<span style = "background-color: rgb (255, 204, 0);"> if (serialPort-> bytesAvailable () <0) </ span>
{
serialPortAssitant.ReciveWidget-> setText ("No data");
return;
}

Ranch
Ranch
<span style = "background-color: rgb (255, 204, 0);"> QByteArray temp; </ span>
<span style = "background-color: rgb (255, 204, 0);"> temp = serialPort-> readAll (); </ span>

QString receiveMsg;
if (IsReceiveByHex)
receiveMsg = ByteArrayToHexStr (temp);
else
receiveMsg = temp;
Ranch
if (receiveMsg.isEmpty ())
{
if (IsShowCurrentTime)
{
errorInfo = "";
currentTime = QDateTime :: currentDateTime ();
timeinfo = currentTime.toString ("yyyy__MM__d__hh: mm: ss");
errorInfo = QString :: fromLocal8Bit ("Error message");
errorInfo + = timeinfo;
errorInfo + = "\ n";
}
else
{
errorInfo = "";
errorInfo = QString :: fromLocal8Bit ("Error message");
errorInfo + = "\ n";
}
serialPortAssitant.ReciveWidget-> append (errorInfo + QString :: fromLocal8Bit ("No data read \ n"));
return;
}

// The number of bytes received is based on the initial bytes
reciveCount + = temp.count ();
serialPortAssitant.status-> RxByte-> setText (QString :: number (reciveCount));
QString showReciveMsg;
if (IsShowCurrentTime)
{

currentTime = QDateTime :: currentDateTime ();
timeinfo = currentTime.toString ("yyyy__MM__d__hh: mm: ss");
showReciveMsg + = QString :: fromLocal8Bit ("Receive data:");
showReciveMsg + = timeinfo;
showReciveMsg + = "\ n";
showReciveMsg + = receiveMsg;
}
else
{
showReciveMsg = QString :: fromLocal8Bit ("Receive data:");
showReciveMsg + = receiveMsg;
}
serialPortAssitant.ReciveWidget-> append (showReciveMsg);

}

void CameraSerialPort :: onReadyRead ()
{
Read ();
} 





1, before reading the data, you need to determine whether the buffer has data, data to read the data



2, if there is data, all read out the buffer data







    • Summarize





Roughly about QT serial port class is introduced, mainly Qserialport and qserialportinfo two classes of use, of course, also need to understand qiodevice.





Qt (6)--Qt5.5.1 implements Universal serial Port program


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.