Reprint: http://blog.csdn.net/yafeilinux/article/details/4717706 Yafeilinux
(Note: Our programming environment is under Windows XP, in the Qt creator, if under Linux or directly with the source code, the program slightly different, please make your own changes.) )
In QT there is no specific serial control class, now most people use third-party written Qextserialport class, we are also used in this class. We can go.
http://sourceforge.net/projects/qextserialport/files/
To download, you can also go to download I uploaded to the Internet:
http://download.csdn.net/source/1762781 or http://www.qtcn.org/bbs/read.php?tid=22847
The file downloaded to is: Qextserialport-1.2win-alpha.zip
The contents are as follows:
We only need to use 6 of these files under Windows:
Qextserialbase.cpp and Qextserialbase.h,qextserialport.cpp and Qextserialport.h,win_qextserialport.cpp and Win_ Qextserialport.h
If you only need to change win_qextserialport.cpp and win_qextserialport.h to Posix_qextserialport.cpp and Posix_qextserialport.h under Linux.
The first part:
Here we will cover the detailed programming process, here we first give the complete program, and then go to the second part of the sentence analysis.
1. Open Qt Creator, new QT4 Gui application, project name set to mycom, other Use default option.
(Note: The established project path cannot be in Chinese.) )
2. Copy the above mentioned 6 files to the project folder, as.
3. Add these 6 files to the project.
In Qt Creator, on the left side of the file list, right-click the project folder, select Add Existing files in the pop-up menu, add the existing file. Such as:
Select the 6 files in the project folder to add them. Such as.
Add the following file list as shown:
4. Click Mainwindow.ui to add a text Browser to the window to display the information. Such as.
5. Add the header file # include "Win_qextserialport.h" in the corresponding location of mainwindow.h, add object declaration win_qextserialport *mycom; add slot function declaration void readmycom (); When you are finished adding, such as.
6. Add the following statement to the constructor of the Mainwindow.cpp class.
Mainwindow::mainwindow (Qwidget *parent)
: Qmainwindow (parent), UI (new Ui::mainwindow)
{
UI->SETUPUI (this);
struct Portsettings mycomsetting = {baud9600,data_8,par_none,stop_1,flow_off,500};
Define a structure to store the parameters of the serial port
mycom = new Win_qextserialport ("COM1", Mycomsetting,qextserialbase::eventdriven);
Defines the serial port object and passes the parameters to initialize it in the constructor function.
Mycom->open (Qiodevice::readwrite);
Open the serial port in read/write mode
Connect (mycom,signal (Readyread ()), This,slot (readmycom ()));
Signal and slot function correlation, when the serial port buffer has the data, reads the serial port operation
}
Add the following code to the definition of the readmycom () function below.
void mainwindow::readmycom ()//Read serial function
{
Qbytearray temp = Mycom->readall ();
Read all data from the serial buffer to TEMP variable
Ui->textbrowser->insertplaintext (temp);
Display data from the serial port in the window's text browser
}
After the code is added, such as.
At this point, if you run the program, you can already realize the function of reading serial data. We will be the single-chip microcomputer temperature information collected by a series of oral to the computer, the effect of such as.
This is the simplest serial communication program is completed. You can see that it only needs to add a few lines of code, very simple.
Part II:
The previous section has introduced the implementation of the simplest serial receiver program writing, the following will be the program content analysis.
1. The process of operating the serial port should be explained first.
Step One: set the serial port parameters, such as: baud rate, data bits, parity check, stop bit, data flow control and so on.
Step Two: Select the serial port, such as Windows 1 for the serial port "COM1", Linux under the "TtyS0" and so on, and open the serial port.
Step three: read or write the serial port.
Step four: close the serial port.
(Our previous program did not write serial port and shut down the function of the serial port, open the serial is also in the construction function, because it is only to use the simplest way to complete the programming of the serial port. We will revise and refine it later on. )
2. Below we will follow the above operation of the serial port process, the first program to explain the writing.
First, before we write the program, we should look at the 6 files, about what they are, and what the various types of files are related to each other. In the Win_qextserialport.cpp file, we look at its last constructor, and we find that the serial port can be initialized here.
Win_qextserialport::win_qextserialport (const QString & name, const portsettings& settings, Qextserialbase:: Querymode mode) {
Win_handle=invalid_handle_value;
Setportname (name);
Setbaudrate (settings. baudrate);
Setdatabits (settings. DataBits);
Setstopbits (settings. StopBits);
Setparity (settings. Parity);
Setflowcontrol (settings. FlowControl);
SetTimeout (settings. TIMEOUT_MILLISEC);
Setquerymode (mode);
Init ();
}
It has three parameters, where the first parameter, const QString & name, should be the name of the serial port, is the QString type, we can use the serial port 1 namely "COM1", do not have too much explanation. Here we focus on the second and third parameters.
Second, we look at the position of the second parameter.
Choose Edit->find/replace->all projects in the QT creator menu, for example.
In the dialog box that pops up, enter the content you want to find portsettings, such as.
When you click Search, you can show the location of all portsettings in the project below. Such as.
When we click on the first one, we can see that there is a struct portsettings in the qextserialbase.h file, such as.
We double click on this to enter the corresponding file. Such as.
struct portsettings
{
Baudratetype baudrate;
Databitstype databits;
Paritytype Parity;
Stopbitstype stopbits;
Flowtype FlowControl;
Long timeout_millisec;
};
We can see that the parameters of serial port initialization are defined in this structure, and for the definitions of Baudratetype and other types, we can see on the structure that they are multiple enumeration variables. Such as.
At this point we should understand that this structure is to achieve the serial port parameter settings.
Third, define the serial port parameters.
Baudratetype baudrate;
Baud rate setting, we set to 9600, that is, the program with BAUD9600;
Databitstype databits;
Data bit set, we set to 8 bits data bit, namely data_8;
Paritytype Parity;
Parity set, we set to no calibration, that is par_none;
Stopbitstype stopbits;
Stop bit setting, we set to 1 bit stop bit, namely stop_1;
Flowtype FlowControl;
Data flow control settings, we set to no data flow control, that is, Flow_off;
Long timeout_millisec;
Delay setting, we set to delay 500ms, that is 500;
This then writes out the sentence in the program:
struct Portsettings mycomsetting = {baud9600,data_8,par_none,stop_1,flow_off,500};
We define a struct variable mycomsetting and initialize it.
Four, set the third parameter.
We first find its definition position in qextserialbase.h, as in the above method.
You can see that the query mode is also an enumeration variable, there are two options, we choose the second EventDriven, event-driven.
Here we can define the variables of the Win_qextserialport class, which is the sentence:
mycom = new Win_qextserialport ("COM1", Mycomsetting,qextserialbase::eventdriven);
It completes the serial port selection and the initialization of the serial port.
Five, write open serial function and read serial function.
Looking at the Win_qextserialport.h file, we will find that the Win_qextserialport class inherits from the Qextserialbase class.
Looking at the Qextserialbase.h file, we will find that the Qextserialbase class inherits from the Qiodevice class.
We look at the Qiodevice class in the QT help, such as.
Some of its contents are as follows. You can see that there are enum openmodeflag {notopen, ReadOnly, WriteOnly, ReadWrite, ..., unbuffered},virtual bool Open (OpenMode mode ), Qbytearray ReadAll () and other content.
The following signal function has void readyread (); It can see if there is any new data coming from the serial port.
So, we can use these functions in this class to operate the serial port.
such as the statement in the program:
Mycom->open (Qiodevice::readwrite);
We called the Open function, and opened the serial port in a readwrite-readable way, and the open function was redefined in win_qextserialport.cpp.
Connect (mycom,signal (Readyread ()), This,slot (readmycom ()));
We correlate the signal readyread (), and write our own slot function readmycom (), when the serial port has data to read the serial operation
void mainwindow::readmycom ()//Read serial function written by oneself
{
Qbytearray temp = Mycom->readall ();
We call the ReadAll () function to read all the data in the string, and we can see that its return value is Qbytearray type
Ui->textbrowser->insertplaintext (temp);
Call the Insertplaintext () function, which is the continuous output of data in the text browser on the window, rather than erasing the previous data before each write
Data, you can see the description of the function in the QT Help
}
So we have finished writing all the statements, and finally only need to add the corresponding header file in the Mainwindow.h file, object declaration, function declaration.
What needs to be explained here is that we must learn to view the files and use the Help document, we do not understand knowledge 1.1 points to understand.
Part III:
The following program makes some improvements on the program written in the first section. Join to open and close the serial port, send data and other functions.
1. Added "Open serial port", "Turn off serial port" "Transmit data" three buttons, add a line edit box. They are named as follows:
The "Open serial port" button is named: openmycombtn
The "Close serial port" button is named: closemycombtn
The "Transmit data" button is named: sendmsgbtn
The row edit box to transfer data is named: Sendmsglineedit
interface such as.
2. Right-click on the "Open serial port" button, select the Go to Slot option, then select the clicked () option and go to its Click event slot function to cut all the statements written in the constructor in the previous program. Then add a few buttons to the state setting statement. As follows:
void Mainwindow::on_openmycombtn_clicked ()
{
struct Portsettings mycomsetting = {baud9600,data_8,par_none,stop_1,flow_off,500};
Define a structure to store the parameters of the serial port
mycom = new Win_qextserialport ("COM1", Mycomsetting,qextserialbase::eventdriven);
Defines the serial port object and passes the parameters to initialize it in the constructor function.
Mycom->open (Qiodevice::readwrite);
Open the serial port in read/write mode
Connect (mycom,signal (Readyread ()), This,slot (readmycom ()));
Signal and slot function correlation, when the serial port buffer has the data, reads the serial port operation
Ui->openmycombtn->setenabled (FALSE); "Open serial port" button is not available after opening serial port
Ui->closemycombtn->setenabled (TRUE); The "Close serial port" button is available after opening the serial port
Ui->sendmsgbtn->setenabled (TRUE); The "Send Data" button is available after opening the serial port
}
In the constructor also add a few buttons to the initial state setting statement, as follows:
Mainwindow::mainwindow (Qwidget *parent)
: Qmainwindow (parent), UI (new Ui::mainwindow)
{
UI->SETUPUI (this);
Ui->closemycombtn->setenabled (FALSE); Start the "Close serial port" button is not available
Ui->sendmsgbtn->setenabled (FALSE); Start the Send Data button is not available
}
After the change, the program looks like this:
Then run the program, the effect is as follows:
3. Enter the slot function for the Click event of the "Close serial port" button and "Send Data" button as described above, and change the following.
void mainwindow::on_closemycombtn_clicked ()//close serial port slot function
{
Mycom->close (); Close the serial port, the function is defined in the Win_qextserialport.cpp file
Ui->openmycombtn->setenabled (TRUE); The "Open serial port" button is available when the serial port is closed
Ui->closemycombtn->setenabled (FALSE); "Close serial port" button is not available after closing serial port
Ui->sendmsgbtn->setenabled (FALSE); The "Send data" button is not available after you close the serial port
}
/***********************************/
void mainwindow::on_sendmsgbtn_clicked ()//Send data slot function
{
Mycom->write (Ui->sendmsglineedit->text (). TOASCII ());
Writes data from the line edit box to the serial port in ASCII format
}
Procedures such as:
The final effect is as follows:
(send data x to microcontroller, microcontroller returns you send Message is:x)
Part IV:
At the beginning of this article to explain the improvement of the program, at the end of the article will explain some important issues .
1. Add some combo boxes to the window combo box, their names and entries are as follows:
Serial port: Portnamecombobox, Entry: com1,com2
Baud rate: Baudratecombobox, entry is: 9600,115200
Data bit: Databitscombobox, entry: 8,7
Check bit: Paritycombobox, entry: None, odd, even
Stop bit: Stopbitscombobox, entry:
(Note: Double-click on the combo box on the window to add an entry by pressing the "+" sign on the popup dialog.) We just added these entries for demonstration purposes, and you can add them to your needs. )
The modified window looks like this:
2. Change the Click event slot function of the "Open serial port" button.
void Mainwindow::on_openmycombtn_clicked ()
{
QString portname = Ui->portnamecombobox->currenttext (); Get the serial name
mycom = new Win_qextserialport (Portname,qextserialbase::eventdriven);
Defines the serial port object and passes the parameters to initialize it in the constructor function.
Mycom->open (Qiodevice::readwrite); Open the serial port
if (Ui->baudratecombobox->currenttext () ==tr ("9600"))//Set the serial port according to the contents of the combo box
Mycom->setbaudrate (BAUD9600);
else if (Ui->baudratecombobox->currenttext () ==tr ("115200"))
Mycom->setbaudrate (BAUD115200);
Set baud rate
if (Ui->databitscombobox->currenttext () ==tr ("8"))
Mycom->setdatabits (Data_8);
else if (Ui->databitscombobox->currenttext () ==tr ("7"))
Mycom->setdatabits (data_7);
Setting Data bits
if (Ui->paritycombobox->currenttext () ==tr ("none"))
Mycom->setparity (Par_none);
else if (Ui->paritycombobox->currenttext () ==tr ("odd"))
Mycom->setparity (par_odd);
else if (Ui->paritycombobox->currenttext () ==tr ("even"))
Mycom->setparity (Par_even);
Set parity
if (Ui->stopbitscombobox->currenttext () ==tr ("1"))
Mycom->setstopbits (stop_1);
else if (Ui->stopbitscombobox->currenttext () ==tr ("2"))
Mycom->setstopbits (stop_2);
Set Stop bit
Mycom->setflowcontrol (Flow_off); Set up data flow control, we use the default settings without data flow control
Mycom->settimeout (500); Set delay
Connect (mycom,signal (Readyread ()), This,slot (readmycom ()));
Signal and slot function correlation, when the serial port buffer has the data, reads the serial port operation
Ui->openmycombtn->setenabled (FALSE); "Open serial port" button is not available after opening serial port
Ui->closemycombtn->setenabled (TRUE); The "Close serial port" button is available after opening the serial port
Ui->sendmsgbtn->setenabled (TRUE); The "Send Data" button is available after opening the serial port
Ui->baudratecombobox->setenabled (FALSE); Setting individual combo boxes is not available
Ui->databitscombobox->setenabled (FALSE);
Ui->paritycombobox->setenabled (FALSE);
Ui->stopbitscombobox->setenabled (FALSE);
Ui->portnamecombobox->setenabled (FALSE);
}
Here we first get the name of the serial port, and then call another constructor to define the mycom, there is no serial port setting parameters in this constructor. Then open the serial port. Then get the serial port settings data, with Setbaudrate (), such as a series of functions to set the serial port, these functions are defined in the Win_qextserialport.cpp file, such as.
After reading the contents of the previous sections, these functions should be well understood and not explained here. At the end of the few combo boxes that we added are not available, so that they cannot be selected in the case of a serial port opening.
The procedure is as follows:
3. Change the "Close Serial port" button click the slot function of the event.
void Mainwindow::on_closemycombtn_clicked ()
{
Mycom->close ();
Ui->openmycombtn->setenabled (TRUE); The "Open serial port" button is available when the serial port is closed
Ui->closemycombtn->setenabled (FALSE); "Close serial port" button is not available after closing serial port
Ui->sendmsgbtn->setenabled (FALSE); The "Send data" button is not available after you close the serial port
Ui->baudratecombobox->setenabled (TRUE); Set each combo box to be available
Ui->databitscombobox->setenabled (TRUE);
Ui->paritycombobox->setenabled (TRUE);
Ui->stopbitscombobox->setenabled (TRUE);
Ui->portnamecombobox->setenabled (TRUE);
}
Here are just a few statements that make the combo box available when the "Close serial port" button is pressed.
The procedure is as follows:
4. Change the main.cpp file.
#include
#include//Join header file
#include "Mainwindow.h"
int main (int argc, char *argv[])
{
Qapplication A (argc, argv);
QTEXTCODEC::SETCODECFORTR (Qtextcodec::codecforlocale ());
Enable the program to handle Chinese
MainWindow W;
W.show ();
return A.exec ();
}
Because Chinese is used in the above program, in order to make the program recognize Chinese, we need to include these statements in the main function.
The procedure is as follows:
5. Run the program.
After opening the program interface is as follows.
The effect is as follows when you send 1 normally.
Set to "Odd check", after sending 1 effect as. (The received is garbled)
Here, the whole program is finished.
From: http://blog.csdn.net/yafeilinux/article/details/4717706
Important question Description:
(The first program described below refers to the program written in the first part, the second program refers to the third part of the program after the change, the third program refers to the four changes after the program.) )
Issue One: Change the code in the first program.
struct Portsettings mycomsetting = {baud9600,data_8,par_none,stop_1,flow_off,500};
mycom = new Win_qextserialport ("COM1", Mycomsetting,qextserialbase::eventdriven);
These two lines of code are changed to the following line:
mycom = new Win_qextserialport ("COM1", Qextserialbase::eventdriven);
If you run the program again, can you use it? That is the structure of our serial port Setup mycomsetting no use? You can change the baud rate in the structure above from 9600 to 115200, if the structure is useful, then the program will not be able to receive data, but you run the program again, is that it?
So it seems that we do not set the serial port is useless, the default serial port settings is what? Let's look at the next question first.
Problem Two: Open the third program and the second program at the same time.
(Note: The serial port of two programs cannot be opened at the same time, so open a serial port of a program to turn off the serial port of another program.) )
We first on the third program by default settings to open the serial port, send data 1. Then close the serial port, open the serial port on the second program, send data 1. You can see that the information received on each of the two programs is correct. Such as.
We close the second program on the serial port, and then set the third program to the odd check, and then open the serial port, send data 1, you can see its received data display garbled. Then we close the third program on the serial port, open the second program on the serial port, send data 1, you will be surprised to find that the information it received is garbled. Such as.
What the hell is going on here? We can also go to the Internet to download other serial assistant for the experiment, you can also change the baud rate for the experiment. The result of all the results can only be: we use that structure as a parameter passed, and the serial port is not set, and the program runs using the serial port setting is the system previously reserved settings. So, why is this so? Let's look at one of the following questions.
Question three: Change the code in the third program.
Mycom->open (Qiodevice::readwrite);
After you put the statement that sets the serial port,
Connect (mycom,signal (Readyread ()), This,slot (readmycom ()));
This sentence before running the program again. You will find that the serial port setting function of the program has not worked. Do you know the reason now?!
In fact, the above three questions is a problem, it concludes that, when the serial port program, the first to open the serial port and then set it, otherwise the settings will not work. Therefore, it should be explained here, the first and the second program are not quite correct, the correct method should be like a third program, the first definition of the Win_qextserialport class object, and then open the serial port, and then use the several settings function to set the serial port.
here, the whole article is over. For some of these problems are only my personal opinion, because the level is limited, so there may be deviations in understanding, or errors, but also the vast number of netizens criticized. I'm writing this article to make it easier for QT beginners to write serial communication programs with QT, and to master some of the skills of QT writing programs. If you have learned a little bit from my article, then my article will have its meaning.
Finally, if you like my writing style, and beginner qt, you can view the QT Creator series tutorials in my space and hope to help you get started.
Turn: QT Programming serial Communication program full text explanation