Click to See Complete Forum and Search --> : RS-232 Problem


Marko Moilanen
October 15th, 2002, 01:32 AM
Hey!

I have a little problem. I need to read and write to serial port but i'm doing something wrong in port initialization (setting up baudrate etc.)??? because after that SetCommState(...) function returns error. Can anyone help me?

Here's my code:

HANDLE hPort;
DCB dcbPort;
BOOL b_State;
DWORD dwError;

hPort = CreateFile("COM1",GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL ); //Opening serial port

b_State = GetCommState(hPort,&dcbPort);
if(!b_State)
{
dwError = GetLastError();
CloseHandle(hPort);
return 0;
}
else
{

dcbPort.DCBlength = sizeof(DCB);
dcbPort.BaudRate = CBR_9600; // Baudrate
dcbPort.ByteSize = 8; // Size of one byte data
dcbPort.Parity = NOPARITY; // Parity-control
dcbPort.StopBits = 1; // Stopbits
}

b_State = SetCommState(hPort,&dcbPort); //This returns false
if(!b_State)
{
dwError = GetLastError(); //Error number is 87
MessageBox(NULL,"Not working","!!!!",MB_OK);
CloseHandle(hPort);
return 0;
}

while(m_bListenThreadContinue)
{

}

CloseHandle(hPort);

cup
October 15th, 2002, 03:01 AM
It is probably the FILE_ATTRIBUTE_NORMAL which is throwing it. FILE_ATTRIBUTE_NORMAL should not be specified with any other flags. Try removing FILE_ATTRIBUTE_NORMAL.

kchaaoub
October 15th, 2002, 03:50 AM
you can use serial.cpp and serial.h from

http://www.codeguru.com/network/serial.shtml

this article and samples are contributed by Tom Archer and Rick Leinecker. The serial communication became very easy by using this class. take a look you 'll be very satisfied


[URL=http://www.codeguru.com/network/serial.shtml]

Chuck Bruce
July 29th, 2004, 03:20 PM
I fought this same problem for two days, and I can tell you what I found was my problem. Setting the dcbPort.StopBits value to '1' is apparently a bad value. Use the literal value ONESTOPBIT instead. That fixed it for me!

I realize that this post is about two years too late for the original questioner, but hopefully this will help someone else later!

JESUS REIGNS!