Writing a Serial Communication Library for Windows - CSerialComm Class
(Page 3 of 6 )
The CSerialComm class uses eight member functions to achieve the above mentioned functionality. Six are explained above and the rest two GetBytesRead and GetBytesWritten allow you to keep track of the amount of Transacted bytes. The class Diagram of the class is as below:

Figure 1: The CSerialComm Class Diagram
The code for the methods is below and is self describing if you’ve understood the above theory.
BOOL CSerialComm::OpenPort(CString strPortName)
{
strPortName= "//./" +strPortName;
m_hComm = CreateFile (strPortName,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
0,
0);
if (m_hComm==INVALID_HANDLE_VALUE)
{
::MessageBox(NULL,_T("Cannot open Communication Port"),_T("Com Port Error"),MB_OK | MB_ICONERROR);
return FALSE;
}
else
{
return TRUE;
}
}
The OpenPort() member function opens a communication port for data transmission. The parameter to be passed to this function is a string containing the port name. For example "com1" for COM1, "com2" for COM2 etc. If the function succeeds the return value is true, otherwise it is false.
BOOL CSerialComm::ConfigurePort(DWORD BaudRate,
BYTE ByteSize,
DWORD dwParity,
BYTE Parity,
BYTE StopBits)
{
if((m_bPortReady = GetCommState(m_hComm, &m_dcb))==0)
{
::MessageBox(NULL,_T("GetCommState Error"),_T("Error"),MB_OK | MB_ICONERROR); CloseHandle(m_hComm);
return FALSE;
}
m_dcb.BaudRate = BaudRate;
m_dcb.ByteSize = ByteSize;
m_dcb.Parity = Parity ;
m_dcb.StopBits = StopBits;
m_dcb.fBinary = TRUE;
m_dcb.fDsrSensitivity = FALSE;
m_dcb.fParity = dwParity;
m_dcb.fOutX = FALSE;
m_dcb.fInX = FALSE;
m_dcb.fNull = FALSE;
m_dcb.fAbortOnError = TRUE;
m_dcb.fOutxCtsFlow = FALSE;
m_dcb.fOutxDsrFlow = FALSE;
m_dcb.fDtrControl = DTR_CONTROL_DISABLE;
m_dcb.fDsrSensitivity= FALSE;
m_dcb.fRtsControl = RTS_CONTROL_DISABLE;
m_dcb.fOutxCtsFlow = FALSE;
m_dcb.fOutxCtsFlow = FALSE;
m_bPortReady = SetCommState(m_hComm, &m_dcb);
if(m_bPortReady ==0)
{
::MessageBox(NULL,_T("SetCommState Error"),_T("Error"),MB_OK | MB_ICONERROR); CloseHandle(m_hComm);
return FALSE;
}
return TRUE;
}
The ConfigurePort () member function configures a communication port for data transmission. The parameters to be passed to this function are given next.
Next: DWORD BaudRate, Parity >>
More Code Examples Articles
More By Digvijay Chauhan