Full text explanation 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 directly, you can modify it 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

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

You can also download my uploaded files 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:

The following describes the specific process of programming. Here we first provide the complete program, and then analyze it in the second part one by one.

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 directory, for example,.

3. Add these 6 files to the project.

In QT creator, right-click the files in the left region and select Add existing files from the shortcut menu to add existing files. For example:

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

After adding the file list, see the following:

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

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

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 the number of workers in the serial port

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

// Define the serial object, pass the number of arguments, and initialize the object 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 in the following example.

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

{

Qbytearray temp = mycom-> readall ();

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

UI-> textbrowser-> insertplaintext (temp );

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

}

After adding the Code, for example.

In this case, the program can be executed to read data from the serial port. We transmit the temperature information of the MCU serial set to the computer through the serial port. The effect is as follows.

This completes the simplest serial communication program. It is easy to see that it only requires several lines of code.


Part 2:

The previous section describes how to write the simplest serial receive program. The following sections will analyze the program content.

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

Step 1:Set the number of serial ports, 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 provide the serial port writing and closing function. Opening the serial port is also completed in the constructor, because it is only to complete the compilation of the serial port program in the simplest way. We will modify and keep it intact later .)

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

First, before coding, we should look at the six files to check 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 ();

}

It has three segments, the first of which is const qstring & name. It should be the serial port name, which is the qstring type. We can use Serial Port 1, that is, "COM1 ", do not describe too much. We will mainly study the second and third vertex numbers below.

Second, we can view the location of the second vertex number.

In the QT creator menu, select edit-> Find/replace-> all projects, for example,.

In the pop-up dialog box, enter the portsettings, for example.

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

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

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 this struct defines the number of segments initialized by the serial port. For the baudratetype and other types, we can see above this struct that they are multiple enumeration variables. For example,.

At this time, we should make it clear that this structure is used to set the serial number.

Third, define the number of serial ports.

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 vertex number.

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 serial port selection and serial port initialization.

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, for example,.

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 from the serial port. The returned value is of the qbytearray type.

UI-> textbrowser-> insertplaintext (temp );

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

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

}

In this way, we have finished writing all the statements. Finally, we only need to add the corresponding header file, object declaration, and function declaration in the mainwindow. h file.

Here, we must note that we must learn to view documents and help documents, and clarify what we do not know about 1.1 points.

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 three buttons: "enable serial port", "Disable serial port", and "Transfer Data", and added a line edit box. Their names are as follows:

Name "open serial port" button: 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.

For example, use.

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 statements written in the constructor in the previous program here. Then, add several button status setting statements. For example:

Void mainwindow: on_openmycombtn_clicked ()

{

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

// Define a struct to store the number of workers in the serial port

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

// Define the serial object, pass the number of arguments, and initialize the object 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); // after opening the serial port, the "open serial port" button is unavailable.

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

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

}

Add several button initial State setting statements to the constructor, for example:

Mainwindow: mainwindow (qwidget * parent)

: Qmainwindow (parent), UI (new UI: mainwindow)

{

UI-> setupui (this );

UI-> closemycombtn-> setenabled (false); // start "Close serial port" button unavailable

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

}

After the change, the program is shown as follows:

At this time, execute the program, the effect is as follows:

3. Follow the above method to go To the slot function of the Click Event of the "Close serial port" button and "send data" button, and change it 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); // After the serial port is disabled, the "send data" button is unavailable.

}

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

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

}

For example:

The final effect 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 describe the improvements to the program.Important questions.

1. Add some combo boxes to the form. 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 on the form and press "+" in the pop-up dialog box to add entries. We only add these entries for demonstration purposes. You can add them as needed .)

The modified form is shown in the following figure:

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 the number of arguments, and initialize the object 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); // after opening the serial port, the "open serial port" button is unavailable.

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

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

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 name of the serial port, and then call another constructor to define mycom. This constructor does not set the serial port number. Then open the serial port. Then obtain the settings 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, for example.

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 program is as follows:

3. Change the "Close serial port" button to 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); // After the serial port is disabled, the "send data" button is unavailable.

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 program is as follows:

4. Change the main. cpp file.

# Include

# Include // Add a 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 ();

}

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

The program is as follows:

5. Execute the program.

The following is the program interface.

The effect after sending 1 is as follows.

Set to "odd check". The effect 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 );

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? That indicates that mycomsetting, the structure set by our serial port, is not practical? You can change the baud rate in the above struct from 9600 to 115200. If this struct is practical, the program cannot receive data again, but you can execute 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 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 another 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, open the serial port, and send data 1. We can see that the data we received 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 exactly is this? We can also download other serial assistants from the Internet to perform experiments, or change the baud rate. The conclusion drawn from all the results is that after we use the struct as the serial data transmission, we have not set the serial port, the serial port settings used by the program execution are the settings that have been reserved by the system. So why? Let's take a 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 ()));

Before this sentence, execute 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 the problems 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. I am writing this article only to make it easier for people who have just started learning QT to use QT to write serial communication programs and to master some tips for coding QT. Suppose you have learned a knowledge point from my article, so 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

Full text explanation of serial communication program written by QT

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.