Click here to Skip to main content
15,905,420 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to send string through the serial port i tried to send
char lpBuffer[] = "100001111";
i could send it successfully. but when I try below I am getting a crazy result. What method I can use....?

What I have tried:

void setDataToPort(string strData)
{
	BOOL   Status;

	//char lpBuffer[] = "100001111";
	
	string mStr = "100001111";
	
	string *srData = &mStr;

	DWORD dNoOFBytestoWrite;         // No of bytes to write into the port
	DWORD dNoOfBytesWritten = 0;     // No of bytes written to the port
	dNoOFBytestoWrite = sizeof(*srData);
	
	

	Status = WriteFile(hComm,        // Handle to the Serial port
		(LPCVOID*)srData,     // Data to be written to the port
		dNoOFBytestoWrite,  //No of bytes to write
		&dNoOfBytesWritten, //Bytes written
		NULL);
	
// I am getting below results
/*

Hö†.100001111.ÌÌÌÌÌÌ........Hö†.100001111.ÌÌÌÌÌÌ........hý†.100001111.ÌÌÌÌÌÌ........hý†.100001111.ÌÌÌÌÌÌ........ý†.100001111.ÌÌÌÌÌÌ........ý†.100001111.ÌÌÌÌÌÌ.........õ†.100001111.ÌÌÌÌÌÌ........

*/



}
Posted
Updated 9-Jun-17 22:12pm

 
Share this answer
 
There is no need to use C++ string classes. Just use char buffers instead. This avoids problems with wide char strings (e.g. CString with MFC). When using using string classes use the corresponding functions to access the characters (e.g. string::c_str).

Avoid using helper variables and casts. This makes the code unreadable and is prone to errors (the number of characters to be written in your case).

This should do the job:
char lpBuffer[] = "100001111";
DWORD dNoOFBytestoWrite;
// You have to pass the number of characters to be written.
// sizeof() of would only work with byte arrays of fixed size when
//  all array items are initialised.
DWORD dNoOfBytesWritten = strlen(lpBuffer);
Status = WriteFile(hComm, lpBuffer, dNoOFBytestoWrite, &dNoOfBytesWritten, NULL);

But I guess that you will still get a result similar to the one shown in your question. It looks like you are receiving the data and did not append a NULL byte before printing the received data out so that the print function can not determine the end of the string. A possible solution would be sending also the NULL byte:
DWORD dNoOfBytesWritten = strlen(lpBuffer) + 1;
But this is rather uncommon with serial communications using printable characters. Instead, change your receiving function to append a NULL byte when there are no more data.
 
Share this answer
 

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