Serial Communication Programming Based on API functions
The serial communication programming methods used include: using communication controls, embedding assembly in advanced languages, and using API functions. In these methods, use the serial port communication compiled by the API FunctionProgramMost efficient and flexible. Serial Communication Programming uses three types of API functions: API functions related to serial communication, multi-threaded API functions, and API functions that implement message mechanisms. The following describes these API functions respectively.
1. APIs related to serial communication
Windows communication generally uses wosa (Windows
Based on the open services architecture (windows open service system) model, applications located in the upper layer exchange data by calling various communication APIs and device drivers located in the lower layer. The following describes the API functions in the sequence of general serial communication procedures.
1.1 open the serial port
The Win32 operating system regards the serial port as a file, so the createfile function is used to open the serial port. The first parameter of this function indicates the name of the file to be opened. For serial port operations, such as COM1 and com2. The second parameter is set in read/write mode. To read/write the serial port, set this parameter to generic_read | generic_write. The third parameter value must be 0, indicating that the serial port is not shared with other applications. The fourth parameter points to a security
Attribute structure, usually set to null. The fifth parameter specifies how to open a file. When opening a device (the serial port is a device), this parameter must be specified as open_existing. The sixth parameter specifies the file attributes and related tags, but the only meaningful setting for the serial port is file_flag_overlapped or 0. The last parameter must be null. If the function successfully opens the serial port, the created handle is returned, which is used for subsequent configuration, read/write, and other operations on the serial port; otherwise, the invalid_handle_value is returned.
1.2 set serial port
After the serial port is opened, you can perform a series of initialization settings. The most basic initialization settings are implemented through the getcommstate and setcommstate functions. First, call the getcommstate function to obtain the current serial port configuration fill Device Control Block (DCB), and then change several important parameters in the DCB structure, such as the baud rate, data bit, stop bit, and check bit, to values that meet the actual design requirements, finally, use setcommstate to reset the serial port with the changes just made. Set the serial port I/O buffer size using the setupcomm function. The higher the communication rate, the greater the buffer should be set, but cannot exceed the device driver's capacity.
Processing range. Another important setting is the serial port timeout setting. Unpredictable events may occur for unknown reasons in communication, such as sudden interruption during data reception or sudden stop of data sending. If you do not take it seriously, these conditions may cause the I/O thread to be suspended or the thread to be blocked infinitely. Windows provides security measures for such problems. It can determine whether the communication is abnormal and handle the problem through timeout settings. Therefore, timeout settings are particularly important in serial communication. The timeout setting process is divided into two steps. First, set the five members in the commtimeouts structure, and then call the setcommtimeouts function to set the timeout value. The five members of commtimeouts structure are: Read serial port interval timeout, read Serial Port Total timeout multiplier, read Serial Port Total timeout constant (MS) write Serial Port Total timeout multiplier, write Serial Port Total timeout constant (MS ).
1.3 read/write serial port
After setting, you can use readfile and writefile to perform read and write operations on the serial port. Before calling the read/write operation function, use the clearcommerror function to clear the error mark and obtain the current serial port status. Read/write operations are divided into synchronous and overlapping I/O (asynchronous ). During synchronous execution, the function is returned only after the operation is completed. During overlapping I/O operations, the called function is returned immediately even if the operation is not completed, time-consuming I/O operations are performed in the background. It can be seen that the synchronization operation thread is blocked, and the efficiency is low. It can only be used in scenarios with low communication requirements. We generally use highly efficient overlapping I/O operations. Set the sixth parameter of the createfile function to file_flag_overlapped to specify the read
The file and writefile functions overlap I/O execution. When using overlapping I/O, you also need to specify an overlapped structure for the read/write function. This structure has five data members. For serial communication, the offset and hevent members are very important. Offset indicates the file pointer offset. When overlapping I/O operations are performed, the system cannot automatically maintain the file pointer. Therefore, you must manually adjust the file pointer in the program by offset. Hevent indicates whether the read/write operation is complete. If the operation is completed,
The hevent is set to the signal state; otherwise, the hevent is set to the non-signal state. Finally, when I/O operations overlap, the return value of the read/write function is false, which does not indicate that the operation fails. You should call the getlasterror function to analyze the returned results. If
If the returned value of the getlasterror function is error_io_pending, the operation is incomplete (not an operation failure ). We will use the wait function to wait for the Operation to complete. Two typical wait functions are waitforsingleobject and getoverlappedresult. The similarities of the function are that the hevent Member of the overlapped structure specified by the read/write operation is set to the signal state (that is, the operation is completed). The difference is that waitforsingleobject is configurable timeout, however, the result of overlapping I/O operations cannot be obtained. getoverlappedresult is used to obtain the result of overlapping I/O operations, but timeout cannot be set. Therefore, the two are often used in combination. After the waitforsingleobject operation is completed, use getoverlap-pedresult to get the operation result.
1.4 close the serial port
The serial port is a non-shared resource. When an application opens a serial port, the resource is exclusive so that other applications cannot access it until the application releases the serial port. Therefore, you must disable the serial port after completing the serial port operation. Close the serial port and use the closehandle function. The unique parameter of this function is the handle created when the serial port is opened using createfile.
2. multi-threaded API functions
Windows is multi-threaded and preemptible
). In Windows, the runtime instance of an executable program is called process ). A process can have multiple threads. In Windows, CPU time slices are allocated by threads, and the allocation mechanism is the preemptive multitasking method.
For time-consuming work such as reading and writing serial ports, using multithreading technology, it is a common solution to create auxiliary threads to manage serial ports. In this way, the data read can be processed while reading and writing through the serial port. If a single thread is used, you need to wait until the serial port read/write operation is complete and the whole process is blocked. Multithreading can avoid this situation.
Multithreading also brings about some new problems, one of which is thread synchronization. If the synchronization problem is not solved well, the program stability will be greatly affected. Several commonly used thread synchronization methods include mutex, semaphore, event, and critical
Section ). In practical application, I used event objects in combination with Windows message mechanism to synchronize threads, and received good results.
Create a thread function as createthread. Use the suspendthread and resumethread functions to suspend and wake up the thread. Create the event function as createevent. Use the setevent and resetevent functions to set the event to the signal and non-signal states to synchronize the thread. The setcommmask and waitcommevent functions are often used for auxiliary thread management of serial communication. Setcommmask is used to specify a series
Columns of event monitoring serial ports, such as monitoring whether data is received by the serial port; waitcommevent is used to wait for the specified event to occur. In practice, the author uses setcommmask in the auxiliary thread to specify the serial port to monitor and receive data events, and then uses waitcommevent to send a message to the main thread when the serial port actually receives data, the data received by the main thread.
3. API functions for message mechanism implementation
Windows is a message-driven operating system.A message is a command sent to a program by a device.
It executes an operation. The specific operation is implemented by the message processing function. You can customize message transmission between threads. Use wm_user (whose value is equal to 0x0400) as the base number and then sequentially Add the sequence number. For example:
Wm_commnotify equ wm_user + 100 h (the value smaller than wm_user is the reserved value of windows, which is greater than this value for users ).
The previous section has mentioned the use of the message mechanism in serial communication programming. Here we will continue to explain how to implement the message mechanism. The programming tool used by the author is Borland's c ++
Builder (BCB), so the implementation of the message mechanism has its own special features. There are three methods to implement messages in BCB: Message ingMeSsage
MapOverload the dispatch virtual member function of tobject, The wndproc method of tcontrol, and the APPLI
The onmessage method of cation. The third method is the fastest, because generally, BCB automatically generates a tapplication class instance for each program. When messages arrive in the BCB program, the tapplication object is obtained first. It is passed to form only after being passed through tapplication. The first two methods are the tform method, which is obviously later than the onmessage method that directly loads the application. All we have to do is define our own message processing functions:
Void _ fastcall tform1MyonmessagetAgmsg & msg
Bool & handled
Tmessage message
Switch (msg. Message)
Case wm_commnotify
Message. MSG = msg. message;
Message. wparam = msg. wparam;
Message. lparam = msg. lparam;
// AddCode
Handled = true;
Break;
Then, when the window is created, use the custom message processing function to reload the onmessage method of the application:
Void _ fastcall tform1Formcreate (tobject Sender)
Application-> onmessage
= Myonmessage;
In this way, you can receive custom messages in the program and process them accordingly.
It is worth noting that application-> onmessage cannot capture non-queue messages, and it cannot capture messages sent directly to the window using sendmessage because it does not pass the message queue. However, you can use another API function called postmessage to send messages. The message sent by this function is a queue message.
4 Conclusion
Using multi-thread, message mechanism, and overlapping I/o API functions for serial programming can realize real-time and efficient serial communication and provide a useful reference for the development of serial port drivers in windows. &
References
1 FAN yi zhi. Jiang Wenxian. Chen Li Yuan. c ++
Serial Communication Control between builder and RS-232 [M]. Tsinghua University Press, 2002
2 Huang Jun and others. Delphi serial communication programming [M]. People's post and telecommunications Press, 2001
3 Zhang Zhiming. Li rongyan. Wang Lei. Research on Serial Communication Programming Technology in Win32 environment [J]. Computer Application Research
2002; 9