Complete text description of serial communication program written by QT

Source: Internet
Author: User

(Note: our programming environment is in Windows XP and implemented in QT creator. If the program is written in Linux or in source code, the program is slightly different. Change the program by yourself .)

 

There is no specific serial control class in QT. Most people now use the qextserialport class written by a third party. We also use this class here. We can go

Http://sourceforge.net/projects/qextserialport/files/

To download, you can also download my uploaded to the Internet:

Http://download.csdn.net/source/1762781 or http://www.qtcn.org/bbs/read.php? Tid = 22847

The downloaded file is: qextserialport-1.2win-alpha.zip

Its content is as follows:

In Windows, we only need to use the following six files:

Qextserialbase. cpp and qextserialbase. H, qextserialport. cpp and qextserialport. H, win_qextserialport.cpp and win_qextserialport.h

In Linux, replace win_qextserialport.cpp and win_qextserialport.h with posix_qextserialport.cpp and posix_qextserialport.h.

 

Part 1:

Next we will introduce the detailed process of programming. Here we will first provide the complete program, and then go to the second part to perform a sentence-by-sentence analysis.

1. Open QT creator, create a qt4 GUI application, set the project name to mycom, and use the default options for others.

(Note: The created Project path cannot contain Chinese characters .)

2. Copy the six files mentioned above to the project folder, as shown in.

3. Add these 6 files to the project.

In the left-side file list of QT creator, right-click the project folder and select Add existing files from the shortcut menu to add existing files. For example:

Select the six files in the project folder and add them. For example.

Shows the list of added files:

4. Click mainwindow. UI and add a text browser to the window to display information. For example.

5. Add the header file # include "win_qextserialport.h" in the corresponding position of mainwindow. H, add the object declaration win_qextserialport * mycom; Add the slot function declaration void readmycom (); after adding the slot function, as shown in.

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 struct to store parameters of the serial port

Mycom = new win_qextserialport ("COM1", mycomsetting, qextserialbase: eventdriven );

// Define the serial object, PASS Parameters, and initialize it in the constructor

Mycom-> open (qiodevice: readwrite );

// Enable the serial port in read/write mode

Connect (mycom, signal (readyread (), this, slot (readmycom ()));

// Correlation between signals and slot functions. When the serial port buffer has data, read the serial port.

}

Add the definition of the readmycom () function below and add the following code.

Void mainwindow: readmycom () // read the serial port Function

{

Qbytearray temp = mycom-> readall ();

// Read all data in the serial buffer to the Temporary Variable temp

UI-> textbrowser-> insertplaintext (temp );

// Display serial port data in the text browser of the window

}

After adding the code, as shown in.

Now, if you run the program, you can read data from the serial port. We transmit the temperature information collected by the microcontroller from the serial port to the computer, as shown in figure.

This completes the simplest serial communication program. You can see that it only needs to add a few lines of code, which is very simple.


Part 2:

The previous section describes how to write the simplest serial receiving program. The following describes the program content.

1. First, describe the procedure for operating the serial port.

Step 1:Set serial parameters, such as baud rate, data bit, parity, stop bit, and data flow control.

Step 2:Select the serial port. For example, if the serial port 1 in Windows is "COM1" and the Linux is "ttys0", open the serial port.

Step 3:Read or write serial ports.

Step 4:Disable the serial port.

(The previous program did not write the serial port or disable the serial port function. Opening the serial port is also done in the constructor, because it is only to write the serial port program in the simplest way. We will modify and improve it later .)

2. Next we will explain the compilation of the first program according to the above procedure of serial port operation.

First, before writing a program, we should look at the six files to see what is in them and what is the relationship between the classes of each file. In the win_qextserialport.cpp file, let's look at its last constructor and we will 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 ();

}

There are three parameters in total. The first parameter const qstring & name should be the name of the serial port, which is the qstring type. We can use Serial Port 1, that is, "COM1. Next we will mainly study the second and third parameters.

Second, we can view the location of the second parameter.

Choose edit-> Find/replace-> all projects from the QT creator menu, as shown in.

In the displayed dialog box, enter portsettings, as shown in.

Click search to display the positions of all portsettings in the project. For example.

Click the first entry to see a struct portsettings in the qextserialbase. h file, as shown in.

Double-click this item to enter the corresponding file. For example.

Struct portsettings

{

Baudratetype baudrate;

Databitstype databits;

Paritytype parity;

Stopbitstype stopbits;

Flowtype flowcontrol;

Long timeout_millisec;

};

We can see that each parameter for serial port Initialization is defined in this struct. For the definition of baudratetype and other types, we can see above this struct that they are multiple enumeration variables. For example.

At this time, we should understand that this structure is to implement serial port parameter settings.

Third, define the serial port parameters.

Baudratetype baudrate;

The baud rate is set to 9600, that is, baud9600 is used in the program;

Databitstype databits;

Set the data bit to an 8-Bit Data bit, that is, data_8;

Paritytype parity;

For parity settings, we set it to non-parity, that is, par_none;

Stopbitstype stopbits;

The stop bit is set to one stop bit, that is, stop_1;

Flowtype flowcontrol;

Data Flow Control settings, we set to no data flow control, that is, flow_off;

Long timeout_millisec;

Latency settings: we set the latency to 500 ms, that is, 500;

In this way, the sentence in the program is written:

Struct portsettings mycomsetting = {baud9600, data_8, par_none, stop_1, flow_off, 500 };

We defined a struct variable mycomsetting and initialized it.

Fourth, set the third parameter.

We first find the location defined by the above method, in qextserialbase. H, for example.

We can see that the query mode is also an enumeration variable. There are two options: select the second eventdriven and event-driven.

Here, we can define the variables of the win_qextserialport class, that is:

Mycom = new win_qextserialport ("COM1", mycomsetting, qextserialbase: eventdriven );

It completes the selection of the serial port and the initialization of the serial port.

Fifth, write and enable the serial function and read the serial function.

View the win_qextserialport.h file and we will find that the win_qextserialport class inherits from the qextserialbase class.

View the qextserialbase. h file. We will find that the qextserialbase class inherits from the qiodevice class.

We can view the qiodevice class in the help of QT, as shown in.

Some of the content is as follows. We can see that Enum exists.Openmodeflag{Notopen, readonly, writeonly, readwrite,..., unbuffered}, virtual boolOpen(OpenmodeMode), QbytearrayReadall.

The following signal functions contain void.Readyread(); It can check whether new data is sent from the serial port.

Therefore, we can use these functions in this class to operate the serial port.

For example, the statement in the program:

Mycom-> open (qiodevice: readwrite );

// We call the OPEN function and use readwrite to open the serial port. This open function is redefined in win_qextserialport.cpp.

Connect (mycom, signal (readyread (), this, slot (readmycom ()));

// We associate the signal readyread () with the self-written slot function readmycom (). When data is transmitted from the serial port, we can read the serial port.

Void mainwindow: readmycom () // read serial port function written by myself

{

Qbytearray temp = mycom-> readall ();

// Call the readall () function to read all data in the serial port. The returned value is of the qbytearray type.

UI-> textbrowser-> insertplaintext (temp );

// Call the insertplaintext () function to output data continuously in the text browser of the window, instead of clearing the previous

// Data. You can view the description of this function in the help of QT.

}

In this way, all the statements are written, and you only need to add the corresponding header file, object declaration, and function declaration to the mainwindow. h file.

Here we must note that we must learn to view documents and help documents and understand what we do not know.

Part 3:

The following Program has made some improvements in the program written in the first part. Added functions such as opening and disabling the serial port and sending data.

1. added the "enable serial port", "Disable serial port", and "Transfer Data" buttons, and added a line edit box. Their names are as follows:

The "open serial port" button is named openmycombtn.

The "Close serial port" button is named closemycombtn.

The "Transfer Data" button is named sendmsgbtn.

The row editing box for data transmission is named sendmsglineedit.

UI.

2. right-click the "open serial port" button, select the go to slot option, and select the clicked () option to go to its Click Event slot function, cut all the statements written in the constructor in the previous program here. Then, add a few button status setting statements. As follows:

Void mainwindow: on_openmycombtn_clicked ()

{

Struct portsettings mycomsetting = {baud9600, data_8, par_none, stop_1, flow_off, 500 };

// Define a struct to store parameters of the serial port

Mycom = new win_qextserialport ("COM1", mycomsetting, qextserialbase: eventdriven );

// Define the serial object, PASS Parameters, and initialize it in the constructor

Mycom-> open (qiodevice: readwrite );

// Enable the serial port in read/write mode

Connect (mycom, signal (readyread (), this, slot (readmycom ()));

// Correlation between signals and slot functions. When the serial port buffer has data, read the serial port.

UI-> openmycombtn-> setenabled (false); // The "open serial port" button is unavailable after the serial port is opened.

UI-> closemycombtn-> setenabled (true); // after opening the serial port, the "Close serial port" button is available.

UI-> sendmsgbtn-> setenabled (true); // the "send data" button is available after the serial port is opened.

}

Add several buttons in the constructor to set the initial state 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 unavailable

UI-> sendmsgbtn-> setenabled (false); // The start "send data" button is unavailable.

}

Shows the program after the change:

In this case, run the program with the following effect:

3. Press the above method to go to the "Close serial port" button and the "send data" button to click the event slot function. The changes are as follows.

Void mainwindow: on_closemycombtn_clicked () // close the serial port slot function

{

Mycom-> close (); // close the serial port. This function is defined in the win_qextserialport.cpp file.

UI-> openmycombtn-> setenabled (true); // After the serial port is closed, the "enable serial port" button is available.

UI-> closemycombtn-> setenabled (false); // After the serial port is closed, the "Close serial port" button is unavailable.

UI-> sendmsgbtn-> setenabled (false); // the "send data" button is unavailable after the serial port is disabled.

}

/***********************************/

Void mainwindow: on_sendmsgbtn_clicked () // data sending slot function

{

Mycom-> write (ui-> sendmsglineedit-> text (). toascii ());

// Write the data in the row editing box to the serial port in ASCII code format

}

Programs such:

The final result is as follows:

(Send data X to the microcontroller, And the microcontroller returns you send message is: X)

 

Part 4:

At the beginning of this article, we will first explain the improvements to the program.Important questions.

1. Add some combo boxes to the window. Their names and entries are as follows:

Serial Port: portnamecombobox, entry: COM1, com2

Baud Rate: baudratecombobox, entry: 9600,115200

Data bit: databitscombobox, entry: 8, 7

Check bit: paritycombobox, entry: None, odd, even

Stop bit: stopbitscombobox, entry: 1, 2

(Note: double-click the combo box in the window and press "+" in the pop-up dialog box to add entries. We only add these entries for demonstration. You can add them as needed .)

The modified window is as follows:

2. Change the Click Event slot function of the "open serial port" button.

Void mainwindow: on_openmycombtn_clicked ()

{

Qstring portname = UI-> portnamecombobox-> currenttext (); // obtain the serial name

Mycom = new win_qextserialport (portname, qextserialbase: eventdriven );

// Define the serial object, PASS Parameters, and initialize it in the constructor

Mycom-> open (qiodevice: readwrite); // open the serial port

If (ui-> baudratecombobox-> currenttext () = tr ("9600") // you can set the serial port based on the content of the combo box.

Mycom-> setbaudrate (baud9600 );

Else if (ui-> baudratecombobox-> currenttext () = tr ("115200 "))

Mycom-> setbaudrate (baud115200 );

// Set the baud rate

If (ui-> databitscombobox-> currenttext () = tr ("8 "))

Mycom-> setdatabits (data_8 );

Else if (ui-> databitscombobox-> currenttext () = tr ("7 "))

Mycom-> setdatabits (data_7 );

// Set the data bit

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 the parity

If (ui-> stopbitscombobox-> currenttext () = tr ("1 "))

Mycom-> setstopbits (stop_1 );

Else if (ui-> stopbitscombobox-> currenttext () = tr ("2 "))

Mycom-> setstopbits (stop_2 );

// Set the stop bit

Mycom-> setflowcontrol (flow_off); // sets the data flow control. We use the default settings without data flow control.

Mycom-> setTimeout (500); // sets the latency.

Connect (mycom, signal (readyread (), this, slot (readmycom ()));

// Correlation between signals and slot functions. When the serial port buffer has data, read the serial port.

UI-> openmycombtn-> setenabled (false); // The "open serial port" button is unavailable after the serial port is opened.

UI-> closemycombtn-> setenabled (true); // after opening the serial port, the "Close serial port" button is available.

UI-> sendmsgbtn-> setenabled (true); // the "send data" button is available after the serial port is opened.

UI-> baudratecombobox-> setenabled (false); // you can specify the unavailability of each combo.

UI-> databitscombobox-> setenabled (false );

UI-> paritycombobox-> setenabled (false );

UI-> stopbitscombobox-> setenabled (false );

UI-> portnamecombobox-> setenabled (false );

}

Here we first get the serial port name, and then call another constructor to define mycom. This constructor does not have the serial port setting parameters. Then open the serial port. Then, get the settings data of the serial port and use setbaudrate (); and other functions to set the serial port. These functions are defined in the win_qextserialport.cpp file, as shown in.

After reading the previous sections, I should be very familiar with these functions. I will not explain them here. At last, we made unavailable settings for the added combo boxes so that they cannot be selected when the serial port is opened.

The procedure is as follows:

3. Change the "Close serial port" button and click the event slot function.

Void mainwindow: on_closemycombtn_clicked ()

{

Mycom-> close ();

UI-> openmycombtn-> setenabled (true); // After the serial port is closed, the "enable serial port" button is available.

UI-> closemycombtn-> setenabled (false); // After the serial port is closed, the "Close serial port" button is unavailable.

UI-> sendmsgbtn-> setenabled (false); // the "send data" button is unavailable after the serial port is disabled.

UI-> baudratecombobox-> setenabled (true); // you can specify the availability of each combo.

UI-> databitscombobox-> setenabled (true );

UI-> paritycombobox-> setenabled (true );

UI-> stopbitscombobox-> setenabled (true );

UI-> portnamecombobox-> setenabled (true );

}

Here we only add some statements that make the combo box available after the "Close serial port" button is pressed.

The procedure is as follows:

4. Change the main. cpp file.

# Include

# Include // Add the header file

# Include "mainwindow. H"

Int main (INT argc, char * argv [])

{

Qapplication A (argc, argv );

Qtextcodec: setcodecfortr (qtextcodec: codecforlocale ());

// Enable the program to process Chinese Characters

Mainwindow W;

W. Show ();

Return a.exe C ();

}

Because the above program uses Chinese, in order to enable the program to recognize Chinese, we need to add these statements to the main function.

The procedure is as follows:

5. Run the program.

The program interface is as follows.

After sending 1 normally, the effect is as follows.

Set it to "odd check". The result of sending 1 is as follows. (Garbled characters are received)

At this point, the entire program is finished.

Important questionsNote:

(The first program mentioned below refers to the program written in the first part, and the second program refers to the program after the third part is changed, the third program refers to the program after the fourth part is changed .)

Question 1: 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 );

If the two lines of code are replaced by the following line:

Mycom = new win_qextserialport ("COM1", qextserialbase: eventdriven );

Run the program again. Is it still usable? Does that mean that the structure mycomsetting set by the serial port is useless? You can change the baud rate in the above struct from 9600 to 115200. If this struct is useful, the program cannot receive data again. However, you can run the program again, right?

In this case, the settings for the serial port are useless. What is the default serial port settings? Let's look at the next question first.

Question 2: Open the third program and the second program at the same time.

(Note: The serial ports of the two programs cannot be opened at the same time. Therefore, when opening the serial ports of one program, you must disable the serial ports of the other program .)

First, open the serial port in the third program according to the default settings and send data 1. Close the serial port, open the serial port on the second program, and send data 1. We can see that the information received on both programs is correct. For example.

We close the serial port on the second program, set it to odd check on the third program, then open the serial port, and send data 1. We can see that the received data is garbled. In this case, we close the serial port on the third program, open the serial port on the second program, and send data 1. You will be surprised to find that the information it receives is garbled. For example.

What the hell is going on? We can also download other serial assistants from the Internet to perform experiments, or change the baud rate. The conclusion from all the results is that the serial port is not set after the struct is passed as the parameter, and the serial port settings used by the program running are previously reserved by the system. So why? Let's look at the following question.

Question 3: change the code in the third program.

Mycom-> open (qiodevice: readwrite );

After setting the serial port statement,

Connect (mycom, signal (readyread (), this, slot (readmycom ()));

And then run the program. You will find that the serial port setting function of the program is no longer effective. Do you know why ?!

In fact, the above three problems are one problem. The conclusion is that when writing a serial program, you must enable the serial port before setting it. Otherwise, the setting will not work. Therefore, it should be noted that the first and second programs are both incorrect. The correct method should be like the third program, first define the win_qextserialport class object, and then open the serial port, use those settings to set the serial port.

The entire article is over. Some of these questions are my personal opinions. Due to the limited level, there may be deviations or errors in understanding. I also ask some netizens to criticize and correct them. The purpose of this article is to allow beginners of QT to easily write serial communication programs using QT and to master some skills in QT programming. If you have learned a knowledge point from my article, then this article has its significance.

Finally, if you like my writing style and are new to QT, you can view the QT creator series tutorials in my space, hoping to help you get started.

Here you can download the PDF document: http://download.csdn.net/source/1763251

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.