2003-7-9 7:56:18 PCVC.NET WANGXI Readings: 30453 Serial port is a data transmission channel between the commonly used computer and external serial devices, because serial communication is convenient
It is easy, so it is widely used. We can use the communication function provided by the Windows API to write high portability
Serial communication program.
In Win16, you can open, close, and in OpenComm, CloseComm, and WriteComm.
Read and write the serial port. However, in Win32, serial port and other communication devices are treated as file processing, and the serial port is opened, closed.
And the API function used by reading and writing is the same as the function of the operation file. The serial port can be opened via the CreateFile function
Turn off the serial port through the Closefile function, through the Commprop, DCB structure, getcommproperties,
SetCommproperties, getcommstate and setcommstate and other functions set the serial port status, through the function
Readfile and Writfile read and write serial ports.
VC 6.0 is one of the mainstream languages developed by Windows applications, which has a good graphic design
Interface and support object-oriented programming methods. This article combines one example how to use it in VC 6.0
Win32 API implements a serial communication program.
Realization principle
Examples of this article come from a cement delivery system, in the system, you need to collect through the total sensor
The hun weight value is incorporated into the computer so that the system makes the corresponding processing. This requires serial communication to complete the acquisition
Data transfer work.
For serial communication devices, Win32 API supports two I / O operations for synchronous and asynchronous. Synchronous operation
The program is relatively simple, but the I / O operation function cannot return before the I / O operation end, which will hang the call thread
Up until the I / O operation ends. Asynchronous operation is relatively complex, but it allows time-consuming I / O operations in the background
However, it will not hang up the call thread, which is quite appropriate to improve the response speed of the calling thread in the case of large data volume.
Effective. Asynchronous operation is particularly suitable for both multiple serial devices for I / O operation and simultaneous settings
Read / write operation. The basic idea of these two ways of operation is similar, which will be targeted for synchronous operation.
A specific communication program design is given, while briefly explaining how asynchronous I / O operations.
Initialization of serial equipment
The initialization of serial devices is implemented using the CreateFile function. This function obtains a serial device handle and
Communication parameter settings, including setting output / reception buffer size, timeout control, and event monitoring.
// Serial device handle;
Handle hCOMDEV = 0;
// Serial port open sign;
Bool bopen = false;
// Thread synchronization event handle;
Handle HEVENT = 0;
Bool setupsyncom ()
{
DCB DCB;
CommTIMEOUTS TIMEOUTS;
// The device has been opened
IF (Bopen) Return False;
// Open COM1
IF ((hCOMDEV = Createfile ("Comde", genericread | genericwrite, 0, null, open
EXISTING, FILETTRIBUTENORMAL, NULL) ==
INVALID-Handle-Value
Return False;
/ / Set timeout control
Setcommtimeouts; HCOMDEV, & TIMEOUTS;
/ / Set the size of the receiving buffer and output buffer
SetupComm (HCOMDEV, 1024, 512);
/ / Get the value of the default DCB structure
GetcommState (HCOMDEV, & DCB);
// Set the baud rate is 9600 bps
DCB.BAUDRATE = CBR9600; // Set no parity check
Dcb.fparity = noparity;
/ / Set the data bit is 8
DCB.BYTESIZE = 8;
// Set a stop bit
DCB.Stopbits = onestopbit;
/ / Monitor the incorrect of the serial port and receive two events of characters
Setcommmask (HCOMDEV, EVERR | EVRXCHAR);
/ / Set the serial device control parameters
SetCommState (HCOMDEV, & DCB);
// The device has been opened
Bopen = True;
// Create an incident of manual reset, no signal
HEVENT = CREATEEVENT (NULL, FALSE, FALSE,
"Watchevent");
// Create an event monitoring thread to monitor the serial event
AfxBeginThread (CommwatchProc, PParam);
}
When setting the parameters of the serial DCB structure, you do not have to set each value. First read the default parameter settings of DCB
Set, then only modify the necessary parameters, other parameters are available. Since synchronous I / O operation is performed on the serial port
Therefore, the waitcommEvent function will not return unless the event is specified. In serial equipment
The initialization finally establishes a separate monitoring thread to monitor the serial entry, so as not to hang up the current call thread,
The PPARAM can be a window pointer that processes an event.
If you want to perform an asynchronous I / O operation, when you open the device handle, the sixth parameters of CreateFile should add file -flag.
overlapped logo.
Data transmission
Data transmission utilizes the WriteFile function. For synchronous I / O operation, its last parameter can be
NULL; while the asynchronous I / O operation, its last parameter must be a pointer to the Overlapped structure,
Get the current operating state by the Overlapped structure.
Bool WriteComm (LPCVOID LPSNDBuffer, DWORD
DWBYTESTOWRITE)
{// lpsndbuffer is the sending data buffer pointer,
DWBYTESTOWRITE is the length of the byte that will be sent.
// The device has been opened
Bool bwritestate;
/ / The number of bytes actually sent
DWORD DWBYTESWRITTEN
// The device is not open
IF (! Bopen) Return False;
BWRITESTATE = Writefile (HCOMDEV, LPSNDBuffer,
Dwbytestowrite, & dwbyteswritten, null;
IF (! bWriteState || dwbytestowrite! = dwbyteswritten)
//Failed to send
Return False;
Else
//Sent successfully
Return True;
}
Data reception
The task of receiving data is completed by the ReadFile function. This function reads data from the serial port receiving buffer.
Before reading the data, first get the number of bytes in the receiving buffer with the ClearcomMerror function. Synchronize when receiving data
The difference between asynchronous reading is the same as sending data.
DWord Readcomm (LPVOID LPINBUFFER, DWORD
DWBYTESTOREAD)
{// lpinbuffer is a buffer pointer to receive data, DWBYTESTOREAD is the data length that is ready to read (word
Section number)
// Serial device status structure
COMSTAT COMSTAT;
DWORD DWBYTESREAD, DWERRORFLAGS;
// The device is not open
IF (! Bopen) Return 0;
// Read the current state of the serial device
Clearcommorror (HCOMDEV, & DWERRORFLAGS, & Comstat);
// The data length that should be read DWBYTESREAD = min (dwbytestoread, comstat.cbinque);
IF (DWBYTESREAD & GT0)
// read data
IF (! Readfile (HCOMDEV, LPINBUFFER, DWBYTESREAD, & DWBYTESREAD, NULL)
DWBYTESREAD = 0;
Return DwbytesRead;
}
Event monitoring thread
The event monitoring thread monitors the serial entry event. When the monitoring event occurs, the monitoring thread can be
SendMessage or Registration (PostMessage) to the window class processed by the event (referring to the PPARAM
Ding).
Uint CommWatchProc (LPVOID PPARAM)
{DWORD DWEVENTMASK = 0; // Event incident;
While (Bopen)
{// Waiting for the event of monitoring
Waitcommevent (HCOMDEV, & DWEVENTMASK,
NULL);
IF (DWEventmask & EvRXCHAR) ==
EvRxChar)
After ... // After receiving the character event, you can register this message to the window class with PPARAM.
IF (DWEventmask & Everr) == EVERROR)
... // Processing when an error occurs
}
STEVENT (HEVENT);
// signal, indicate the end of the monitoring thread
Return 0;
}
Close serial device
When the entire application ends or no longer uses a serial device, the serial device should be turned off, including abpatient
Piece monitoring, place the device to open the logo Bopen to False to end the event monitoring thread, clear the send / receive buffer
District and closing the device handle.
Void CloseSyncomm ()
{
IF (! bopen) return;
// End the event monitoring thread
Bopen = false;
Setcommmask (hCOMDEV, 0);
/ / Cancel event monitoring, at which time Waitcommmevent in the monitoring thread will return
WaitforsingleObject (HEVENT, INFINITE);
// Waiting for the surveillance thread to end
CloseHandle (HEVENT); // Close the event handle
/ / Stop sending and receiving data, and clears the sending and receiving buffer
PurgeComm (HCOMDEV, PURGE-TXABORT |
Purge-RXAbort | Purge-Txclear |
Purgerxclear;
// Close the device handle
CloseHandle (HCOMDEV);
}
Small knot
The above given the basic idea of using the Win32 API design serial communication, the string of this synchronous I / O operation
Asynchronous I / O operations can be performed slightly. In practical applications, we can communicate these serial communication
Functions and member variables are added to an existing CWND class or derived class to implement serial communication, or design a new
Serial communication class to include these member functions and member variables. In short, use the Win32 API to design a satisfaction
Various serial communication programs required.