Hey,

This may be real basic and Im just drawing a blank. How would you process a byte of info recieved over a serial port. I am writing a char*, recieving 1 (4 bytes) char at a time. I would like to return the entire read back as a char*. Here is that part of the code.

char *Read()
{
	DWORD myReadEvent;											
	DWORD bytesRead;											
	char  myReadByte;										
	char *myIncomingMessage = "";								

	if(!SetupPort(1200, myReadCom))
		cout << "Error setting up the port." << endl;

	else
	{
		if(!SetCommMask(myReadCom, EV_RXCHAR))
			cout << "Could not set read mask." << endl;

		if(WaitCommEvent(myReadCom, &myReadEvent, NULL))
		{
			do
			{
				if(ReadFile(myReadCom, &myReadByte, 1, &bytesRead, NULL))
					//strncat_s(myIncomingMessage, sizeof(myIncomingMessage), myReadByte, 1);
					cout << "Byte Read. Process it. << endl;
				else
					cout << "Read message error." << endl;
			}
			while(bytesRead);
		}
	}

	return myIncomingMessage;
}

void Write(char *myWriteByte)
{
	DWORD bytesWritten;

	if(!SetupPort(1200, myWriteCom))
		cout << "Error setting up the port." << endl;

	WriteFile(myWriteCom, myWriteByte, 1, &bytesWritten, NULL);

	return;
}

Thanks.

I am writing a char*, recieving 1 (4 bytes) char at a time. I would like to return the entire read back as a char*.

This statement is a bit of cause for worry. Are you really trying to write a pointer rather than the text to which it points? Unless you're on an 'exotic' machine, 1 char is 1 byte. I would wager you've got some fundamental issues to review a bit first.

First you have to allocate memory for the return pointer myIncomingMessage. line 6 only declares the variable, you can't write anything into it until you allocate memory with malloc(), new, or setting it to point to some statically allocated block of memory.

Before doing the read on line 20 you need to find out how many characters are available to be read -- there could be many more than just one. Call the function ClearCommErr and it will fill in a COMSTAT structure which contains the count. Then you can call ReadFile() to read all those bytes.

One problem you have is how to determine when you get all the characters you want ? Does the incoming data contain a terminating character ? How do you know when and if you get all the data ? Just because you get an event from line 16 doesn't mean you get all the data.

After reading the data you have to copy it somewhere. That means you have to allocate memory for myIncomingMessage if that is where you want to copy it.

Comments
That too.

The do while loop should tell me when all the data is read, and seems to work. If there is no bytes left to read, then it drops out of the loop. As for the other questions, Ill have to think so more and get back to you. Thanks for the insight.

This article has been dead for over six months. Start a new discussion instead.