Advertisement

Serial communication issue

Started by May 22, 2023 03:09 AM
3 comments, last by DividedByZero 1 year, 6 months ago

Hi Guys,

I am having some trouble when I try reading data from the serial port in C/C++ in windows.

I have a device that is transmitting a single character once per second and can see it is transmitting correctly if I read the com port in Putty (9600, 8, N, 1).

My own code is somewhat intermittent though. It will periodically display the received character (if I'm lucky), but most of the time won't. I have verified that the ‘serialHandle’ is always valid and as far as my code is concerned is making a valid connection.

dwBytesRead also toggles between 1 and 0 at the same rate as the transmitter (once per second). But the data printed is generally blank.

	int baudrate = 9600;
	int byteSize = 8;
	int stopBits = ONESTOPBIT;
	int parity = NOPARITY;

	// Open serial port
	HANDLE serialHandle;

	serialHandle = CreateFile("\\\\.\\COM9", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

	// Do some basic settings
	DCB serialParams = { 0 };
	serialParams.DCBlength = sizeof(serialParams);

	GetCommState(serialHandle, &serialParams);
	serialParams.BaudRate = baudrate;
	serialParams.ByteSize = byteSize;
	serialParams.StopBits = stopBits;
	serialParams.Parity = parity;
	//serialParams.fDtrControl = DTR_CONTROL_ENABLE;
	SetCommState(serialHandle, &serialParams);
	

	// Set timeouts
	COMMTIMEOUTS timeout = { 0 };
	timeout.ReadIntervalTimeout = 50;
	timeout.ReadTotalTimeoutConstant = 50;
	timeout.ReadTotalTimeoutMultiplier = 50;
	timeout.WriteTotalTimeoutConstant = 50;
	timeout.WriteTotalTimeoutMultiplier = 10;

	SetCommTimeouts(serialHandle, &timeout);

	unsigned char buffer[20] = { 0 };

	DWORD dwBytesRead = 0;

	while (true)
	{


	//	std::cout << ReadFile(serialHandle, buffer, 1, 0, 0);

		if (ReadFile(serialHandle, buffer, 1, &dwBytesRead, 0))
		{
			std::cout << dwBytesRead << "\r\n";
			if(dwBytesRead > 0)
				std::cout << buffer << "\r\n";
		}

		Sleep(10);
	}

If I set the transmitting device to transmit a string, I never get a print out any data whatsoever.

And yes, I am making sure that Putty isn't running during these tests.

Any advice would be greatly appreciated. Many thanks!

Seems that running in Putty primed the port somehow.

I went through and checked the DCB struct when my application was behaving, compared to when it wasn't and adjusted the deeper parameters to match. Usually behaving right after the Putty session ended, then breaking shortly thereafter.

Seems all stable now.

Advertisement

Glad you solved it. It sounded like a flow control issue to me, either at hardware (cable wiring) or at software level.

Yep! Looks like it was using hardware flow control, even though the port in device manager said it was set to none.

This topic is closed to new replies.

Advertisement