Below I have pasted my program. The purpose of the program is to read data from a serial port (in this case COM2) and print it out to the screen. I can't seem to get it to print to the screen. I don't know if the port is really configured properly. Can someone out there take a look at my code and run it to see what the problem is? Thnx in advance! Rachael
#include <windows.h>
#include <string.h>
#include <memory.h>
#include <commdlg.h>
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX 130
// Flow control flaags
#define FC_DTRDSR 0x01
#define FC_RTSCTS 0x02
#define FC_XONXOFF 0x04
char port[5] = "COM2:" ; /* Comm port name. */
char msg[MAX] ; /* Message received from port. */
int n_msg = 0 ; /* Counts bytes to read. */
int n_in ; /* Counts bytes read. */
int ok ; /* Return code from function calls. */
HANDLE hPort ; /* Handle to IO port object. */
DCB dcb ;
COMMTIMEOUTS CommTimeOuts ;
BYTE bSet ;
int main(void) {
// Open comm port
hPort = CreateFile(port,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
0,
NULL) ;
if (hPort == INVALID_HANDLE_VALUE) {
printf("Cannot open IO port (error %d)\n", GetLastError()) ;
return 1 ;
}
// Setup comm port connection
dcb.DCBlength = sizeof(dcb) ;
GetCommState(hPort, &dcb) ;
dcb.BaudRate = 9600 ;
dcb.ByteSize = 8 ;
dcb.Parity = 0 ;
dcb.StopBits = 1 ;
// setup hardware flow control
bSet = (BYTE) ((FC_XONXOFF & FC_DTRDSR) != 0) ;
dcb.fOutxDsrFlow = bSet ;
if (bSet)
dcb.fDtrControl = DTR_CONTROL_HANDSHAKE ;
else
dcb.fDtrControl = DTR_CONTROL_ENABLE ;
bSet = (BYTE) ((FC_XONXOFF & FC_RTSCTS) != 0) ;
dcb.fOutxCtsFlow = bSet ;
if (bSet)
dcb.fRtsControl = RTS_CONTROL_HANDSHAKE ;
else
dcb.fRtsControl = RTS_CONTROL_ENABLE ;
// setup software flow control
bSet = (BYTE) ((FC_XONXOFF & FC_XONXOFF) != 0) ;
dcb.fInX = dcb.fOutX = bSet ;
dcb.XonChar = 0x11 ;
dcb.XoffChar = 0x13 ;
dcb.XonLim = 100 ;
dcb.XoffLim = 100 ;
dcb.fBinary = TRUE ;
dcb.fParity = TRUE ;
SetCommState(hPort, &dcb) ;
// read data from port
do {
n_msg = (n_msg <= MAX ? n_msg : MAX) ;
ok = ReadFile(hPort, msg, n_msg, &n_in, NULL) ;
printf("%s", msg) ;
} while(ok) ;
if (!ok) {
printf("Cannot read message (error %d)\n", GetLastError()) ;
return 1 ;
}
// Cleanup
ok = CloseHandle(hPort) ;
if (!ok) {
printf("Cannot close port handle (error %d)\n", GetLastError()) ;
}
return 0 ;
}