Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was trying to implement a serial port communication, the SetCommState function returns error(0).
I have tried with the following code.
C++
COMMPROP commprop = {0};
COMMTIMEOUTS timeouts = {0};
    m_hComm = CreateFile(_T("COM1"),						// communication port string (COMX)
    GENERIC_READ | GENERIC_WRITE,	// read/write types
    0,								// comm devices must be opened with exclusive access
    NULL,							// no security attributes
    OPEN_EXISTING,					// comm devices must use OPEN_EXISTING
    0,			// Async I/O
    NULL);

if (0 == GetCommProperties(m_hComm,&commprop)) {

    MessageBox(_T("Error in setting params"), _T("Error"), 
    MB_ICONERROR | MB_OK);
}
if (m_hComm == INVALID_HANDLE_VALUE)
{
    // port not found
    MessageBox(_T("Cannot open port"), _T("Error"), 
    MB_ICONERROR | MB_OK);
}
else
{
    MessageBox(_T("Port open"), _T("Info"), 
    MB_ICONINFORMATION | MB_OK);
}

DWORD size =1;
char readBuf[5];
char sendBuf[10];
DCB dcb;

memset(readBuf,0,5);
memset(sendBuf,0,10);
memset(&dcb,0,sizeof(dcb));
dcb.DCBlength=sizeof(dcb);
GetCommState(m_hComm,&dcb);		
dcb.BaudRate=5;
dcb.ByteSize = 8;
dcb.StopBits = ONESTOPBIT;
dcb.Parity = NOPARITY;

if (0 == SetCommState(m_hComm,&dcb))
{
    AfxMessageBox(_T("error on setting baud rate"));
}
while(size ==0)
{
    if(!ReadFile(m_hComm, &readBuf[0], 1, &size, NULL))
    {
        MessageBox(_T("Read Error"), _T("Error"), 
        MB_ICONERROR | MB_OK);
    }
}

Is it valid to use FILE_FLAG_OVERLAPPED when calling the CreateFile method? I cannot identify why this issue happens, Please help me to find the trouble with this code.
Posted
Updated 13-Jul-14 22:18pm
v6
Comments
George Jonsson 7-Jul-14 2:16am    
Have you checked which error you get with GetLastError() ?
That might give you a clue about what is going wrong.

 
Share this answer
 
Comments
LaxmikantYadav 14-Jul-14 4:52am    
Nice link, My +5 :)
Quote:
dcb.BaudRate=5;
What kind of device sends data at 5 baud? :omg:


By the way: it is curious you are checking the m_hComm value after having used it in the GetCommProperties call.
 
Share this answer
 
Comments
Utheen 3-Jul-14 8:40am    
It is for K-line communication. 5 baud i initialization over k-line.
George Jonsson 7-Jul-14 2:16am    
Really not an answer, I think

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900