VC + + Serial communication basic knowledge

Source: Internet
Author: User
Tags readfile

Under Win32, you can implement serial communication in two ways, one is to use ActiveX controls (ActiveX is Microsoft's salutation to a series of strategic object-oriented program technologies and tools, the main technology being the Component Object Model (COM)), which is simple, But less flexible. The second is to call the Windows API function, this method can clearly grasp the mechanism of serial communication, and free and flexible.
In this article we only introduce the API serial communication section.
The operation of the serial port can be operated in two ways: synchronous operation mode and overlapping operation mode (also known as asynchronous operation mode). When synchronizing, the API function blocks until the operation is complete (in multithreaded mode, although it does not block the main thread, but still blocks the listener), and the API function returns immediately after the operation is performed in the background, avoiding thread blocking.
This is done in four steps, regardless of the type of operation:
(1) Open the serial port
(2) Configuring the serial port
(3) Read/write serial
(4) Close the serial port

1. Open the serial port
The WIN32 system extends the concept of a file. Whether it's a file, a communication device, a named pipe, a mail slot, a disk, or a console, all with API functionsCreateFileTo open or create the.
2. Configure the serial port
After opening the communication device handle, it is often necessary to do some initialization configuration work on the serial port. This requires the adoption of aDCBStructure to be carried out. The DCB structure contains information such as baud rate, number of data bits, parity, and stop bits. The DCB structure is used as a buffer when querying or configuring the properties of the serial port.
After you open the serial port with CreateFile, you can callgetcommstatefunction to get the initial configuration of the serial port. To modify the configuration of the serial port, you should modify the DCB structure before callingSetCommStatefunction to set the serial port.
In addition to the settings in BCD, the program generally needs to set the size and timeout of the I/O buffers. Windows uses I/O buffers to stage data for serial input and output. If the rate of communication is high, you should set a larger buffer. CallSetupcommfunction to set the input and output buffer size of the serial port.
When reading and writing serial ports with ReadFile and WriteFile, you need to consider the timeout problem. The function of a timeout is to not read or send a specified number of characters within a specified amount of time, and the operation of ReadFile or WriteFile will still end.
To query the current timeout setting should be calledgetcommtimeoutsfunction, the function fills acommtimeoutsStructure. CallsetcommtimeoutsYou can set timeouts with the contents of a COMMTIMEOUTS structure.
There are two types of timeouts for read-write serial ports: Interval timeout and total timeout. The interval timeout is the maximum delay between two characters at the time of receipt. The total timeout is the maximum time a read-write operation has taken. The write operation only supports the total timeout, while both the read operation timeout is supported. Use the COMMTIMEOUTS structure to specify the timeout for read and write operations.
Before reading and writing the serial port, you need to usePurgeCommThe function empties the buffer.
3, read and write serial port
We useReadFileAndWriteFileRead and write serial.
When reading and writing serial ports with ReadFile and WriteFile, both can be executed synchronously or overlapped. When executed synchronously, the function is not returned until the operation is complete. This means that threads are blocked during synchronous execution, resulting in a decrease in efficiency. When overlapping execution, even if the operation is not completed, both functions return immediately, and the time-consuming I/O operation takes place in the background.
Whether the ReadFile and WriteFile functions are synchronous or asynchronous is determined by the CreateFile function, and if the FILE_FLAG_OVERLAPPED flag is specified when the handle is called CreateFile. The operations that call ReadFile and WriteFile on the handle should be overlapping, and the read and write operations should be synchronous if no overlapping flags are specified. The synchronization or asynchrony of the ReadFile and WriteFile functions should be consistent with the CreateFile function.
The ReadFile function simply reads the specified number of characters into the serial input buffer, even if the operation is complete. The WriteFile function is not only to copy the specified number of characters into the output buffer, but also to wait for these characters to be sent out from the serial port to complete the operation.
If the operation succeeds, both functions return true. It is important to note that when ReadFile and WriteFile return false, it is not necessarily the case that the operation failed and the thread should callGetLastErrorThe function parses the returned result. For example, the function returns False if the action is not completed when the operation is overlapped, and the GetLastError function returns ERROR_IO_PENDING. This indicates that the overlap operation is not yet complete.
Overlapping I/O is very flexible, it can also be blocked (for example, we can set to read to a data to proceed to the next operation). There are two ways to wait for the operation to complete: One method is to use the imageWaitForSingleObjectSo wait for the function to waitOVERLAPPEDThe hevent member of the structure, and the other method is to call the GetOverlappedResult function to wait, which is shown later.
4. Close the serial port
Using the API function to close the serial port is very simple, just use the handle returned by the CreateFile function as a parameter callCloseHandleCan.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

VC + + Serial communication basic knowledge

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.