// Terminal - Very plain terminal program. Simply opens the Port and then // Sends keyboard to COM port, and COM port to screen, forever. // This program demonstrates the use of Comm.lib. CommPortName = "COM2"; // Set this to your valid port #include // Open (try) the port printf("Opening port \"%s\"...",CommPortName); CommHandle = OpenComm(CommPortName,5000,1000); if ( CommHandle < 0 ) { switch( CommHandle ) { case IE_BADID: error = "Invalid or unsupported ID"; break; case IE_BAUDRATE: error = "Unsupported baud rate"; break; case IE_BYTESIZE: error = "Invalid byte size"; break; case IE_DEFAULT: error = "Error in default parameters"; break; case IE_HARDWARE: error = "Hardware Not Present"; break; case IE_MEMORY: error = "Unable to allocate queues"; break; case IE_NOPEN: error = "Device not open"; break; case IE_OPEN: error = "Device already open"; break; default: error = "Unknown Error"; break; } printf("\n\aError %d opening port: %s.\n",CommHandle,error); printf("Press any key to exit..."); getch(); } else { printf("\nComm port is open. You are in Terminal mode.\n"); // Set up routine to Close port in case of sudden program exit atexit("CloseCommHandle"); // set port to 9600 baud, 8 bytes, 1 stop bit, no parity GetCommState(CommHandle,dcb); dcb.Parity = NOPARITY; dcb.BaudRate = 9600; dcb.StopBits = ONESTOPBIT; dcb.ByteSize = 8; SetCommState(dcb); for ( ; ; ) { // forever // Read whatever characters are in keyboard into a buffer if ( kbhit() ) { WriteLen = 0; do { WriteBuf[WriteLen++] = byte(getch()); } while( kbhit() ); // write characters from buffer to comm port if ( WriteLen != WriteComm(CommHandle,WriteBuf,WriteLen,WriteError) || WriteError ) printf("\n\aWrite Error %04X\n",WriteError); } // If any bytes available, then write to the screen if ( (ReadLen = ReadComm(CommHandle,ReadBuf,200,ReadError)) ) fwrite(ReadBuf,ReadLen,stdout); // If there was a read error then report it if ( ReadError ) printf("\n\aRead Error %04X\n",ReadError); } } // This routine will be called to close port when program terminates CloseCommHandle() { CloseComm(CommHandle); }