[Image] [Image] [Image] [Image] [Image] [Image] [Image] [Return] Opening a Serial Port [Return] --------------------------------------------------------------------------- Windows used to have a set of communication (serial) functions which, although not the greatest thing in the world, was a distinct set of functions for that purpose. Win32 made things considerably easier in most aspects, but the functionality was absorbed by generic file functions which, I am assuming, is at least part of the reason why I've heard so many questions concerning COM functions and Win32 systems. Below is a routine used to open a communication port passed to the function as an integer value. First, the port is opened and timeout values are set to "no timeout", meaning ReadFile() will return immediately whether something is waiting to be read or not. Next, the port is set to 9600 baud, no parity, 8 data bits and one stop bit. The open port handle is then returned to the caller assuming there were no errors, in which case INVALID_HANDLE_VALUE is returned. Once the port is open, ReadFile(), WriteFile() and other like functions may be used to send and receive data on the port. CloseHandle() is called to close the port. HANDLE OpenCOMPort( int iPort ) { char szStr[ 64 ]; COMMTIMEOUTS cto; HANDLE hPort; DCB dcb; wsprintf( szStr, "COM%d", iPort ); // Specify port to open hPort = CreateFile( szStr, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL ); if( hPort == INVALID_HANDLE_VALUE ) // Open port or do bad exit return( INVALID_HANDLE_VALUE ); memset( &cto, 0, sizeof(COMMTIMEOUTS) ); // Set timeout values cto.ReadIntervalTimeout = MAXDWORD; // to no timeout SetCommTimeouts( hPort, &cto ); // so ReadFile() doesn't hang memset( &dcb, 0, sizeof(DCB) ); // Initialize the port DCB wsprintf( szStr, "COM%d: baud=9600 parity=N data=8 stop=1", iPort ); dcb.DCBlength = sizeof(DCB); // Specify structure size if( ! BuildCommDCB( szStr, &dcb ) ) // If DCB fails...quit { CloseHandle( hPort ); return( INVALID_HANDLE_VALUE ); } if( ! SetCommState( hPort, &dcb ) ) // Apply DCB to port { // or quit on failure CloseHandle( hPort ); return( INVALID_HANDLE_VALUE ); } return( hPort ); }