![]() |
General Reading »
Hardware & System »
General
Beginner
Non Overlapped Serial Port Communication using Win32By EshwarDemonstration of the use of Win32 function for serial port communication |
VC6, Dev
|
|
Advanced Search |
|
|
|
||||||||||||||||
The purpose of this article is to demonstrate the use of Win32 functions for serial port communication in Visual C++. A C++ class CSyncSerialComm has been developed to implement the following serial port communication operations:
A background in Visual C++ programming is sufficient to grasp the technical details of this article. Access to MSDN is required for looking at the definition of functions, structures etc. used in this article. The article takes a look at only non-overlapped (synchronous) operations supported by Win32. My next article will show implementation of serial port communication using overlapped (asynchronous) structures.
Before starting any communication on a serial port, we must first open a connection. This is achieved by using CreateFile function in Win32. (Those of you familiar with File I/O must be aware of this function.) The following code is used to open a serial port connection in non-overlapped mode.
m_hSerialComm = CreateFile(m_pszPortName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISITING,
0,
NULL);
if (m_hSerialComm == INVALID_HANDLE_VALUE)
//Handle Error Condition
The CreateFile function takes in seven parameters. (Please take a brief moment to look at this function in MSDN.)
GENERIC_READ | GENERIC_WRITE to support both read and write access.
NULL.
OPEN_EXISTING.
FILE_ATTRIBUTE_NORMAL can be used).
NULL as we only support non-overlapped communication. The HANDLE m_hSerialComm that is returned by the CreateFile function can now be used for performing operations like Configure, Read and Write.
After opening connection to a serial port, the next step is usually to configure the serial port connect settings like Baud Rate, Parity Checking, Byte Size, Error Character, EOF Character etc. Win32 provides a DCB struct that encapsulates these settings (refer to MSDN for DCB struct definition). Configuration of the serial port connection settings is performed in the following three steps:
GetCommState function. The function takes in two parameters:
HANDLE we received from the call to the CreateFile function.
DCB structure containing the present settings. DCB structure that we obtained from the previous step, we can modify the necessary settings according to the application needs.
SetCommState method. The following code is a sample shown explaining the use of these functions. (Note: A number of the fields in the DCB struct are not used in the example. A more sophisticated application must allow the client to configure these settings.)
DCB dcbConfig; if(GetCommState(m_hSerialComm, &dcbConfig)) { dcbConfig.BaudRate = dwBaudRate; dcbConfig.ByteSize = 8; dcbConfig.Parity = NOPARITY; dcbConfig.StopBits = ONESTOPBIT; dcbConfig.fBinary = TRUE; dcbConfig.fParity = TRUE; } else //Handle Error Condition if(!SetCommState(m_hSerialComm, &dcbConfig)) //Handle Error Condition
Another important part of configuration of serial port connection settings is setting timeouts. Again, Win32 provides a COMMTIMEOUTS struct for setting Read and Write Timeouts. We are also provided with two functions GetCommTimeouts and SetCommTimeouts to access, modify, and update the timeout settings. The following code can be used to set the serial port timeouts:
COMMTIMEOUTS commTimeout; if(GetCommTimeouts(m_hSerialComm, &commTimeout)) { commTimeout.ReadIntervalTimeout = 1000 * dwReadTimeOutIntervalInSec; commTimeout.ReadTotalTimeoutConstant = 1000 * dwReadTimeOutConstantInSec; commTimeout.ReadTotalTimeoutMultiplier = 1000 * dwReadTimeOutMultiplier; commTimeout.WriteTotalTimeoutConstant = 1000 * dwWriteTimeOutInSec; commTimeout.WriteTotalTimeoutMultiplier = 1000 * dwWriteTimeOutMultiplier; } else //Handle Error Condition if(!SetCommTimeouts(m_hSerialComm, &commTimeout)) //Handle Error Condition
There are many different implementations for reading from a Serial Port Connection. In the CSyncSerialComm class that is provided with this article, serial communication events are used in the implementation of the Read operation. There are three important sets in this implementation.
Read Event using the SetCommMask function. (Note: This function can also be used to set many other different types of serial communication events.) This event is fired when a character is read and buffered internally by Windows Operating System. The SetCommMask function takes in two parameters:
HANDLE we received from the call to the CreateFile function.
Read Event, we use EV_RXCHAR flag. SetCommMask function, we call the WaitCommEvent function to wait for the event to occur. This function takes in three parameters:
HANDLE we received from the call to the CreateFile function.
OVERLAPPED structure. Since, our implementation is for Non-Overlapped communication, it must be set to NULL. ReadFile function to retrieve the bytes that were buffered internally. The ReadFile function takes in five parameters:
HANDLE we received from the call to the CreateFile function.
ReadFile function returns successfully.
NULL for our purpose since we do not deal with non-overlapped mode. In our example, we read one byte at a time and store it in a temporary buffer. This continues until the case when ReadFile function returns successfully and the fourth parameter has a value of 0. This indicates that the internal buffer used by Windows OS is empty and so we stopping reading. The following code shows the implementation of this technique:
std::stringbuf sb; DWORD dwEventMask; if(!SetCommMask(m_hSerialComm, EV_RXCHAR)) //Handle Error Condition if(WaitCommEvent(m_hSerialComm, &dwEventMask, NULL)) { char szBuf; DWORD dwIncommingReadSize; do { if(ReadFile(m_hSerialComm, &szBuf, 1, &dwIncommingReadSize, NULL) != 0) { if(dwIncommingReadSize > 0) { dwSize += dwIncommingReadSize; sb.sputn(&szBuf, dwIncommingReadSize); } } else //Handle Error Condition } while(dwIncommingReadSize > 0); } else //Handle Error Condition
Write operation is easier to implement than Read. It involves using just one function, WriteFile. It takes in five parameters similar to ReadFile function. The second parameter in WriteFile specifies the buffer to be written to the serial port. The following example shows implementation of Write using WriteFile. It writes one byte at a time until all the bytes in our buffer are written:
unsigned long dwNumberOfBytesSent = 0; while(dwNumberOfBytesSent < dwSize /*size of the buffer pszBuf*/) { unsigned long dwNumberOfBytesWritten; if(WriteFile(m_hSerialComm, &pszBuf[dwNumberOfBytesSent], 1, &dwNumberOfBytesWritten, NULL) != 0) { if(dwNumberOfBytesWritten > 0) ++dwNumberOfBytesSent; else //Handle Error Condition } else //Handle Error Condition }
After we finish all our communication with the serial port, we have to close the connection. This is achieved by using the CloseHandle function and passing in the serial port HANDLE we obtained from the CreateFile function call. Failure to do this results in hard to find handle leaks. The follow code snippet explains the use of this function:
if(m_hSerialComm != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hSerialComm);
m_hSerialComm = INVALID_HANDLE_VALUE;
}
I hope my demonstration of the use of Win32 functions in serial port communication will serve as a starting point. I am sure as you browse through MSDN looking for these function definitions, you will come across more sophisticated functions that might be better suited for your application needs.
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 24 Nov 2004 Editor: Smitha Vijayan |
Copyright 2004 by Eshwar Everything else Copyright © CodeProject, 1999-2009 Web17 | Advertise on the Code Project |