In industry control, industrial computer (generally based on Windows platform) often need to communicate with intelligent instruments through the serial port. Serial communication is convenient and easy to use and widely used.
Under normal circumstances, industrial control computer and the intelligent instruments through the RS485 bus communication. RS485 communication mode is Half-duplex, only by the industrial PC as the main node in turn polling the network of Intelligent Control unit nodes. Each communication is made by a PC through the serial port to the Intelligent control unit to release the command, the Intelligent Control unit received the correct command to answer.
Under the Win32, two kinds of programming methods can be used to realize serial communication, one is to use ActiveX control, this method is simple but inflexible. The second is to call the API function of Windows, this method can clearly master the mechanism of serial communication, and free and flexible. This article we only introduce the API serial communication part.
The operation of the serial port can be operated in two ways: synchronous operation mode and overlapping operation mode (also called asynchronous operation mode). When synchronizing, the API functions block until the operation is complete (in multithreading, although the main thread is not blocked, but the listener threads are still blocked), and the overlapping operation, the API function will return immediately, the operation in the background, to avoid the thread blocking.
Regardless of that type of operation, it is generally done in four steps:
(1) Open the serial port
(2) Configure the serial port
(3) Read and write serial port
(4) Close the serial port
(1) Open the serial port
The WIN32 system extends the concept of the file. Whether it is a file, a communications device, a named pipe, a mail slot, a disk, or a console, it is opened or created using API function CreateFile. The prototype of the function is:
HANDLE CreateFile( LPCTSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDistribution,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile);
lpFileName: will open the serial logic name, such as "COM1";
dwDesiredAccess: Specifies the type of serial port access, which can be read, written, or juxtaposed;
dwShareMode: Specifies the shared attribute, which must be set to 0 because the serial port cannot be shared;
lpSecurityAttributes: Refers to the security property structure, the default value is null;
Dwcreationdistribution: Create the logo, the serial operation of the parameter must be set to open_existing;
dwFlagsAndAttributes: A property description that specifies whether the serial port is asynchronous, file_flag_overlapped, which indicates the use of asynchronous I/O, which is 0, which indicates synchronous I/O operations;
hTemplateFile: This parameter must be NULL for the serial port;