Serial Communication Project Note 1

Source: Internet
Author: User
Tags readfile

I. Serial PortAPI

1.Open serial port

You can use the createfile function to open the serial port. There are usually two ways to enable it. One is synchronous (nonoverlapped) and the other is asynchronous (overlapped ).

Handle hcomm;

Hcomm = createfile (gszport, // serial port name

Generic_read | generic_write // read/write

0, // note: the serial port is a non-shared device. This parameter must be set to 0.

0,

Open_existing,

File_flag_overlapped, // asynchronous mode

0 );

If (hcomm = invalid_handle_value) // processing of serial port opening failure

······

2.Configure serial port

The device control block (DCB) structure defines the control settings of serial communication devices. There are three ways to initialize DCB.

    • Use the getcommstate function to obtain the initial value of DCB:

DCB;

Memset (& DCB, 0, sizeof (DCB ));

If (! Getcommstate (hcomm, & DCB ))...... // Handle errors

Else ...... // Ready

    • Use the buildcommdcb function to initialize the DCB structure:

DCB;

Memset (& DCB, 0, sizeof (DCB ));

DCB. dcblength = sizeof (DCB );

If (! Buildcommdcb ("9600, N,", & DCB ))...... // Parameter configuration error

Else ...... // Ready

    • Use the setcommstate function to manually set the initial value of DCB:

DCB;

Memset (& DCB, 0, sizeof (DCB ));

If (! Getcommstate (hcomm, & DCB) return false;

DCB. baudrate = cbr_9600;

3.Traffic Control Device

The following two settings are available for throttling:

    • Hardware traffic control: There are two types of hardware traffic control: DTE/DSR mode and RTS/CTS mode. This is related to the initialization of the DCB structure. We recommend that you use standard and popular traffic control methods, the logical bits of DTE, DSR, RTS, and CTS directly affect the data read/write and the buffer control for sending and receiving data.
    • Software throttling: special characters Xon and xoff are used in serial communication to control serial data sending and receiving.

Note:If you do not set the traffic control mode or software traffic control mode, there is basically no problem, but under the hardware traffic control, the standard rts_control_handshake traffic control method means that when the buffer zone is full, the RTS will automatically turn off and notify the other party to suspend sending. When the buffer zone is empty again, the RTS will automatically on, but in many cases, even if the buffer zone has been cleared after the RTS is turned off, the RTS will not automatically on, causing the other party to stop sending messages. Therefore, if you want to use hardware traffic control, it is best to add the buffer size check after receiving the request. The specific method is to use clearcommerror to return COMSTAT. cbinque: When the buffer zone has been empty, you need to use invoke (escapecommfunction, hcomm, setrts) to re-set RTS to on.

4.Serial Port read/write operations

There are two methods for serial port read/write: synchronous (nonoverlapped) and asynchronous (overlapped ). Synchronous means that the function is returned only after the read/write operation is completed. This may causeProgramNo response, because if an error occurs during reading and writing, an error will occur if no response is returned, and the thread may be stopped in the same place. The asynchronous mode is more flexible. If the read/write operation fails, the read/write operation is suspended and the function returns the result directly. You can use the getlasterror function to find out why the read/write operation fails, therefore, serial port read/write operations are usually asynchronous.

The readfile () function is used to complete read operations. The asynchronous read operations are:

DWORD dwread;

Bool fwaitingonread = false;

Overlapped osreader;

Memset (& osreader, 0, sizeof (osreader ));

Osreader. hevent = createevent (null, true, false, null );

If (osreader. hevent = NULL )...... // Handle errors

If (! Fwaitingonread)

{

If (! Readfile (hcomm, lpbuf, read_buf_size, & dwread, & osreader) // read the serial port

{

If (getlasterror ()! = Error_io_pending )...... // Report error

Else fwaitingonread = true;

}

}

Else

{

// The read is complete. You do not have to call the getoverlappedresults function.

Handleasuccessfulread (lpbuf, dwread );

}

 

// If the read operation is suspended, you can call the waitforsingleobject () function or

// Waitformuntilpleobjects () waits for the read operation to complete or times out,

// Call getoverlappedresult () to obtain the desired information.

If (fwaitingonread)

{

Dwres = waitforsingleobject (osreader. hevent, read_timeout );

Switch (dwres)

{

Case wait_object_0: // complete the read operation

If (! Getoverlappedresult (hcomm, & osreader, & dwread, false ))...... // Error

Else ...... // Read all successfully

Handleasuccessfulread (lpbuf, dwread );

Fwaitintonread = false;

Break;

Case wait_timeout: // The operation has not been completed.

....... // Process other tasks

Break;

Default:

...... // Error

Break;

}

}

Note thatCodeThere are some problems in processing multi-threaded serial ports in the Windows series. After modification, refer to section 1.4 for the code.

5.Close serial port

When the program ends or serial resources need to be released, the serial port must be disabled correctly. Call the closehandle function to disable the serial port handle,

Closehandle (hcomm );

It is worth noting that before closing the serial port, you must ensure that the read/write serial port thread has exited; otherwise, misoperation may occur. The general method is to use the event-driven mechanism to start an event, notifies the serial port read/write thread to force exit.

6.Other problems

Other problems that must be addressed in serial communication are as follows:

    • Detect communication events: Use setcommmask () to set the mask of the communication event to be obtained, and then call waitcommevent () to detect the occurrence of the communication event. The event flag can be set to ev_break \ ev_vts \ ev_dsr \ ev_err \ ev_ring \ ev_rlsd \ ev_rxchar \ ev_rxflag \ ev_txempty.
    • Handling communication Timeout: timeout is an important factor in communication because the data is suddenly interrupted or stopped for some reason during the data receiving process. If the timeout control mechanism is not adopted, the I/O thread will be suspended or blocked infinitely. The timeout setting is divided into two steps. First, set the five variables in the commtimeouts structure, and then call setcommtimeouts () to set the timeout value. For an asynchronous read/write operation, if the operation is suspended, if the read and write operations are completed asynchronously, waitforsingleobject () or waitformultipleobjects () returns wait_object_0, and getoverlappedresult () returns true. You can also use getcommtimeouts () to get the initial value of the system.
    • Error Handling and Communication Status: in serial communication, many errors can be generated. clearcommerror () can be used to detect errors and clear error conditions.
    • When waitcommevent () is returned, it indicates that the status of CTS changes. However, to learn the specific changes, you must use getcommmodemstatus () to obtain more detailed information about the serial line status.

 

II,Serial Port Operation Method

1.Synchronization mode

Synchronous (nonoverlapped) is a relatively simple method, and the code length is significantly less than the asynchronous (overlapped) method. In synchronous mode, the function of reading the serial port tries to read the data of the specified data in the receiving buffer of the serial port until all the data of the specified data is read or the set timeout time is reached. For example:

Commtimeouts timeover;

Memset (& timeover, 0, sizeof (timeover ));

DWORD timemultiplier, timeconstant;

......

Timeover. readtotaltimeoutmultiplier = timemultiplier;

Timeover. readtotaltimeoutconstant = timeconstant;

Setcommtimeouts (hcomm, & timeover );

......

Readfile (hcomm, inbuffer, nwantread, & nrealread, null); // null indicates synchronous file read/write.

If the specified number of data to be read is large and the set timeout time is long, and the number of data in the receiving buffer is small, it may cause thread blocking. To solve this problem, check the cbinque Member of the costat structure. The size of the member is the actual number of waiting members in the receiving buffer. If the nwantread value is equal to COMSTAT. cbinque, it can effectively prevent thread blocking.

2.Asynchronous mode

In the asynchronous mode, the multi-threaded structure of Windows enables the serial port read and write operations in the background, while other parts of the application are executed in the foreground. For example:

Overlapped wroverlapped;

Commtimeouts timeover;

Memset (& timeover, 0, sizeof (timeover ));

DWORD timemultiplier, timeconstant;

...... // Assign values to timemultiplier and timeconstant

Timeover. readtotaltimeoutmultiplier = timemultiplier;

Timeover. readtotaltimeoutconstant = timeconstant;

Setcommtimeouts (hcomm, & timeover );

Wroverlapped. hevent = createevent (null, true, false, null );

......

Readfile (hcomm, inbuffer, nwantread, & nrealread, & wroverlapped );

Getoverlappedresult (hcomm, & wroverlapped, & nrealread, true );

......

Resetevent (wroverlapped. hevent );

The readfile in the code above adopts the asynchronous method, so it only returns the status of whether the data has started to be read, and does not return the actual read data, that is, the nrealread in readfile is invalid. The actual read data is returned by getoverlappedresult. The last parameter value of this function is true, indicating that it is returned to the application only after the asynchronous operation is complete. In this case, the getoverlappedresult and waitforsingleobject functions are invalid.

3.Query Method

That is, a thread in a process regularly queries the receiving buffer of the serial port. If there is data in the buffer, the thread reads the data. If there is no data in the buffer, the thread continues to execute, therefore, it takes a lot of CPU time, which is actually a derivative of the synchronization method. For example:

Commtimeouts timeover,

Memset (& timeover, 0, sizeof (timeover ));

Timeover. readintervaltimeout = maxword;

Setcommtimeouts (hcomm, & timeover );

...... Readfile (hcomm, inbuffer, nwantread, & nrealread, null );

In addition to the variable timeover settings in the commtimeouts structure, the query method and synchronization method are similar in program code, but the two work in different ways. Although readfile adopts the synchronous file read/write mode, since the timeover interval exceeds the time set to maxword, readfile reads all the waiting data in the receiving queue each time, data of up to nwantread bytes can be read at a time.

4.Event-driven Mode

If you have strict response time requirements for port data, you can use the event-driven method. Event-driven mode: sets Event Notifications. When a desired event occurs, Windows sends a notification that the event has occurred. Windows defines the serial communication events in 9, which are commonly used in the following three:

    • Ev_rxchar: receives a byte and puts it in the input buffer.
    • Ev_txempty: The last character in the output buffer, which is sent out.
    • Ev_rxflag: receives event characters (evtchar members in the DCB structure) and puts them in the input buffer.

After setcommmask () is used to create a useful event, the application can call waitcommevent () to wait for the event to occur. Setcommmask can abort waitcommevent. For example:

COMSTAT;

DWORD dwevent;

Setcommmask (hcomm, ev_rxchar );

......

If (waitcommevent (hcomm, & dwevent, null ))

If (dwevent & ev_rxchar) & COMSTAT. cbinque)

Readfile (hcomm, inbuffer, COMSTAT. cbinque, & nrealread, null );

5.Summary

Generally, the query method is the most direct method of reading the serial port. However, regular queries have a fatal weakness, that is, queries occur at regular intervals and may occur too early or too late. When the data changes rapidly, especially when the serial port of the master computer is extended through the expansion board, it is necessary to regularly query all serial ports in turn, which is prone to data loss. Although the smaller the scheduled interval, the higher the real-time data, the more resources the system occupies.

In Windows, the asynchronous file read/write mode is proposed, which improves the file IO speed. It uses the multi-threaded structure of the system, although no asynchronous file I/O operations are implemented in Windows, it can perform asynchronous operations on the serial port. The asynchronous method can improve the overall system performance. This method is recommended for scenarios with high requirements on system robustness.

The event-driven method is an efficient serial port reading method. This method is highly real-time, especially when multiple serial ports are extended, and does not require regular round-robin of all serial ports as in the query method, as in the interrupt method, only when a specified event occurs and the application receives a message from the Windows operating system, the corresponding processing is performed to avoid data loss.

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.