USB to Serial Adapter Reset Detection?

Anyone have a thought on how to check if a USB to Serial Adapter is still connected using the Windows API?

If I have the port open from a program, and the adapter gets unplugged/reset/etc, and I then try to write to the port the write operation will never return. I wonder if there is a simple way (something like .is_open() for files) to check that the device is still properly connected.

-Adam

Got it. In case anyone is in the same situation:

bool checkCom(){
	DCB tempSerialParams={0};
	tempSerialParams.DCBlength=sizeof(tempSerialParams);

	for(int i=0;i<10;i++){
	 	if(GetCommState(comPort, &tempSerialParams)){
			return 1;
		}else{
	       	CloseHandle(comPort);
	        comPort=openSerial(9600,comPortNumber);
		}
		Sleep(50);
	}
	return 0;
}

The above code checks the state of comPort, the handle of your com port. If it is open and working, the function returns true. If not (for example if your USB to Serial adapter has been jostled or otherwise reset) the function tries to reconnect to the port ten times. If it still isn’t connected it returns false, in which case you can display an error message or take other action rather than trying to write to that port and hang your program.

Sweet.

-Adam

Thanks, Adam!

- Ben

Thanks.

Actually there appears to be a weird state between “connected” and “disconnected” where the adapter hangs up (red light goes dim) but still appears connected to Windows. In this state, at least on the computer I’m using, write operations do return, but no data is actually passed through, and changing the state of handshaking lines crashes the program, and takes out all serial ports (even hardware RS-232 ports) until the computer is rebooted.

I think it’s time to distance the adapter from the large brushed DC motors.

-Adam