I am a novice trying to use MS Visual C++ to record data through COM1. The data source is a sensor streaming ASCII characters, and the sensor and the COM1 settings were both checked with hyperterminal.

In the code, I set the CreateFile to open COM1 with normal attributes, and set DCB to match the baud rate, etc. The reading commands look like the following.

//Open a log file
	std::ofstream testfile;
	testfile.open("testfile.txt");

	//Try reading some stuff bytes
	char output[16];
	DWORD readlength = 16, i;
	LPDWORD p_readlength = &readlength;
	for (i=0; i<10;i++){
		ReadFile(com_port,&output,readlength,p_readlength,NULL);
		//Sleep(500);
		std::cout << output<<std::endl;
		testfile <<output<<std::endl;
	}
	testfile.close();
	CloseHandle(com_port);

The resulting test file is mysterious. The first 16 characters of the first line below is how the data looks. Then there are garbage characters. Third line shows jumbled characters.

[01 09.96,022.3]ÌÌÌÌÌÌÌÌ€bQXQˆZ6
[01 09.96,022.3]ÌÌÌÌÌÌÌÌ€bQXQˆZ6
6,022.3]6,022.3]ÌÌÌÌÌÌÌÌ€bQXQˆZ6
[01 09.96,022.3]ÌÌÌÌÌÌÌÌ€bQXQˆZ6
6,022.3]6,022.3]ÌÌÌÌÌÌÌÌ€bQXQˆZ6
[01 09.96,022.3]ÌÌÌÌÌÌÌÌ€bQXQˆZ6
6,022.3]6,022.3]ÌÌÌÌÌÌÌÌ€bQXQˆZ6
[01 09.96,022.3]ÌÌÌÌÌÌÌÌ€bQXQˆZ6
7,022.3]6,022.3]ÌÌÌÌÌÌÌÌ€bQXQˆZ6
[01 09.96,022.3]ÌÌÌÌÌÌÌÌ€bQXQˆZ6

Can someone figure out where the garbage characters and the jumbled data came from? In hyperterminal, the data is shown as continuing stream of characters like [01 09.96,022.3][01 09.92,022.3]... with no space between the brackets. This is the correct format according to the sensor documentation.

Thanks for your help.

ReadFile(com_port,&output,readlength,p_readlength,NULL);
std::cout << output<<std::endl;

In the first line the 4th parameter is nothing more than a pointer to the 3d parameter. declaring another pointer is not necessary. And do not put & symbol whan passing character arrays. ReadFile(com_port, output, readlength, &readlength, NULL); >>std::cout << output<<std::endl;
That's the reason for the garbage characters -- when ReadFile() returns the input buffer is not a null-terminated string. before printing the string either null-terminate it or print it one character at a time. readlength will contain the number of bytes that were read at the port. I would suggest you clear the input buffer before calling ReadLine()

memset(output, 0, sizeof(output));
ReadFile(com_port, output, readlength, &readlength, NULL);

Thanks. That did it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.