The previous DOS system provides the ability to communicate with a serial interface via DOS interrupts and BIOS interrupts. In the Windows environment, the development tools of C + + do not provide specific serial communication control methods like DOS and BIOS, nor allow users to directly control the interruption of the serial port.
In order to ensure resource sharing, Windows system completely takes over all kinds of hardware resources, and the use of interrupts to control the port will destroy the system's multitasking and cause the stability of the system to be affected. However, Windows also provides powerful API functions that enable users to control serial communications indirectly.
1, realize the serial communication related API function
API functions not only provide an operational method for opening and reading communication ports, but also provide a variety of functions to support the various operations of serial communication. Common functions and roles are shown in table 5-1.
Table 5-1 common serial communication API functions and their functions
Function name function
CreateFile Open the serial port
Getcommstate Detection serial port settings
SetCommState Set serial port
BUILDERCOMMDCB fills a device control block with a value in a string
Getcommtimeouts Detection Communication Timeout setting
SetCommTimeouts Set Communication Timeout parameter
Setcommmask set up monitored events
Waitcommevent waits for the monitored event to occur
WaitForMultipleObjects waits for the results of multiple monitored objects
WriteFile Send data
ReadFile Receive data
GetOverlappedResult returns the result of the last overlapping (asynchronous) operation
PurgeComm empty the serial port buffer and exit all related operations
Clearcommerror updates the serial port State structure and clears all serial port hardware errors
CloseHandle Close serial port
2, open the serial port
The function CreateFile was originally used to open a file, but it is also available to open a communication port. As with other objects in the system, the communication port is also identified by a handle. The CreateFile function returns the handle of the communication port being manipulated, and the method is invoked as follows:
HANDLE CreateFile (