Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help Reading data from COM port using Win 32 API

Status
Not open for further replies.

cplsplsprogrammer

Programmer
Apr 18, 2005
42
US
Hello All, I am trying to read data from a serial port in C using Win32 API. I created a thread from the main program which is an NT service and opened the port. Everything is working fine till opening the port and now I tried to read the data from COM port using ReadFile() in overlapped mode. The ReadFile always fails, I can see that the characters are arriving as I used WaitCommEvent() and WaitforSingleObject() to wait till a character arrives. Can anyone help me with this. I am pasting my function below......

DWORD CommThreadProc( LPDWORD param )
{

OVERLAPPED comReader = { 0 };
BOOL fWaitingOnRead = FALSE;
char * lpBuf = "";
DWORD dwRead = 0; // bytes actually read
BOOL Success;
FILE* FilePtr;
DCB dcb = {0};
DWORD dwCommEvent;
COMMTIMEOUTS CommTimeOuts;

printf(" Inside CommThreadProc \n" );
//Opening the COM port
hCommPort = CreateFile( "COM1",
GENERIC_READ,
0,
0,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
0 );

if( hCommPort == INVALID_HANDLE_VALUE )
{
printf( "Error while Opening COM Port \n" );
return 0;
}
//Getting COMM settings
GetCommState( hCommPort, &dcb );

dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;

SetCommState( hCommPort, &dcb );


//Creating overlapped event handle
comReader.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );


SetCommMask( hCommPort, EV_RXCHAR );

BOOL repeat = true;

while( 1 )
{
WaitCommEvent( hCommPort, &dwCommEvent, &comReader );
if( WaitForSingleObject( comReader.hEvent, INFINITE ) == WAIT_OBJECT_0 )
{

do
{
Success = ReadFile( hCommPort, lpBuf, 512, &dwRead, &comReader );

if( !Success )
if (GetLastError() == ERROR_IO_PENDING) // read not delayed?
printf( "Error in reading the file \n");
else
{ // writing the data into a file
FilePtr = fopen( gszFilePath, "a" );

if( FilePtr != NULL )
{
fwrite( &lpBuf, dwRead, 512, FilePtr );
}
else
printf( "Error while opening file" );

fclose( FilePtr );
}
}while( dwRead > 0 );

}
}

CloseHandle( comReader.hEvent );
CloseHandle( hCommPort );


return 1;
}
 
I am getting an error when using ReadFile() : Error 998 (ERROR_NOACCESS). Can anyone tell why I am getting that error message, what should i do to clear that error?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top