• 沒有找到結果。

Implementation of Serial Port Communication

CHAPTER 4 Input Device

4.3 Implementation of Serial Port Communication

In serial data transmission the data is transmitted in serial format with the LSB of the byte to be transmitted, shifted out first among the data bits. The general format for serial transmission is Start Bit + Data Bits + Parity Bit (Optional) + Stop Bit.

The Parity bit is optional. It is used for error checking in

communication. We can enable or disable parity checking by software modifications. Also, we can specify which parity we would like to use, either 'EVEN' or 'ODD' through software.

The various steps to be performed for sending and receiving data through the serial port of a PC are listed below:-

4. Open the communication port.

5. Configure the communication port by setting the Baud rate, parity, no.

of data bits, etc.

6. Set time-outs for communication.

7. Write data to the port.

8. Read data from the port.

9. Close the port.

Open

Before starting any communication on a serial port, we must first open a connection. This is achieved by using CreateFile function in Win32. The following code is used to open a serial port connection in non-overlapped mode.

m_hSerialComm = CreateFile(m_pszPortName,

GENERIC_READ | GENERIC_WRITE,

The CreateFile function takes in seven parameters. (Please take a brief moment to look at this function in MSDN.)

• The first parameter specifies the port name. In our case, this is usually COM, COM2, COM3 or COM4.

• The second parameter must be GENERIC_READ | GENERIC_WRITE to support both read and write access.

• The third parameter must always be 0 for serial port communication because unlike files, serial port access cannot be shared.

• The fourth parameter is used to set security attributes. If no security attribute needs to be specified, just use NULL.

• The fifth parameter must always be set to OPEN_EXISTING.

• The sixth parameter is used to specify flags and attributes (either 0 or FILE_ATTRIBUTE_NORMAL can be used).

• The last parameter must always be 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.

Configuration

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

structure that encapsulates these settings (refer to MSDN for DCB structure definition). Configuration of the serial port connection settings is performed in the following three steps:

1. First, we have to access the present settings of the serial port using the GetCommState function. The function takes in two parameters:

¾ The first parameter is the HANDLE we received from the call to the CreateFile function.

¾ The second parameter is an output parameter, which returns the DCB structure containing the present settings.

2. Next, using the DCB structure that we obtained from the previous step, we can modify the necessary settings according to the application need.

3. Finally, we update the changes by using the SetCommState method.

The following code is a sample shown explaining the use of these functions. (Note: A more sophisticated application must allow the client to configure these settings).

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 structure 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;

There are many different implementations for reading from a Serial Port Connection. Serial communication events are used in the implementation of the Read operation. There are three important sets in this implementation.

1. First, we setup a 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::

¾ The first parameter is the HANDLE we received from the call to the CreateFile function.

¾ The second parameter is used to specify the event type. To specify a Read Event, we use EV_RXCHAR flag

2. After calling the SetCommMask function, we call the WaitCommEvent function to wait for the event to occur. This function takes in three parameters:

¾ The first parameter is the HANDLE we received from the call to the CreateFile function.

¾ The second parameter is an output parameter, which reports the event type that was fired.

¾ The third parameter is a pointer to an OVERLAPPED structure. Since, our implementation is for Non-Overlapped communication, it must be set to NULL.

3. Once this event is fired, we then use the ReadFile function to retrieve the bytes that were buffered internally. The ReadFile function takes in five parameters:

¾ The first parameter is the HANDLE we received from the call to the CreateFile function.

¾ The second parameter is a buffer that would receive the

bytes if the ReadFile function returns successfully.

¾ The third parameter specifies the size of our buffer we passed in as the second parameter.

¾ The fourth parameter is an output parameter that will notify the user about the number of bytes that were read.

¾ The last parameter is always 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 dwIncommingReadSize;

do {

if(ReadFile(m_hSerialComm, &szBuf, 1, &dwIncommingReadSize, NULL) != 0)

} else

//Handle Error Condition } while(dwIncommingReadSize > 0);

} else

//Handle Error Condition Write

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)

Close

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;

}

相關文件