7 #define MAX_PORTNAME_LEN 20
8 #define APP_VERSION_STR "0.01"
10 int main(int argc
, char *argv
[])
12 CHAR txBuffer
[BUFSIZE
];
13 CHAR rxBuffer
[BUFSIZE
];
25 TCHAR szPortName
[MAX_PORTNAME_LEN
];
28 //sscanf(argv[1], "%d", &dwBaud);
29 sscanf(argv
[1], "%d", &nPortNum
);
31 sprintf(szPortName
, _T("COM%d"), nPortNum
);
33 printf("Serial Port Test Application Version %s\n", APP_VERSION_STR
);
34 printf("Attempting to open serial port %d - %s\n", nPortNum
, szPortName
);
35 hPort
= CreateFile(szPortName
,
36 GENERIC_READ
|GENERIC_WRITE
,
43 if (hPort
== (HANDLE
)-1) {
44 printf("ERROR: CreateFile() failed with result: %lx\n", (DWORD
)hPort
);
47 printf("CreateFile() returned: %lx\n", (DWORD
)hPort
);
49 printf("Fiddling with DTR and RTS control lines...\n");
50 for (i
= 0; i
< 100; i
++) {
51 bResult
= EscapeCommFunction(hPort
, SETDTR
);
53 printf("WARNING: EscapeCommFunction(SETDTR) failed: %lx\n", (DWORD
)bResult
);
55 bResult
= EscapeCommFunction(hPort
, SETRTS
);
57 printf("WARNING: EscapeCommFunction(SETRTS) failed: %lx\n", (DWORD
)bResult
);
59 for (j
= 0; j
< 1000; j
++) {
72 bResult
= EscapeCommFunction(hPort
, CLRDTR
);
74 printf("WARNING: EscapeCommFunction(CLRDTR) failed: %lx\n", (DWORD
)bResult
);
76 bResult
= EscapeCommFunction(hPort
, CLRRTS
);
78 printf("WARNING: EscapeCommFunction(CLRRTS) failed: %lx\n", (DWORD
)bResult
);
81 printf("Getting the default line characteristics...\n");
82 dcb
.DCBlength
= sizeof(DCB
);
83 if (!GetCommState(hPort
, &dcb
)) {
84 printf("ERROR: failed to get the dcb: %ld\n", GetLastError());
87 printf("Setting the line characteristics to 9600,8,N,1\n");
88 dcb
.BaudRate
= dwBaud
;
90 dcb
.Parity
= NOPARITY
;
91 dcb
.StopBits
= ONESTOPBIT
;
93 bResult
= SetCommState(hPort
, &dcb
);
95 printf("ERROR: failed to set the comm state: %lx\n", (DWORD
)bResult
);
98 for (i
= 0; i
< BUFSIZE
; i
++) {
99 txBuffer
[i
] = (CHAR
)i
;
100 //printf(" %d ", txBuffer[i]);
104 printf("Writting transmit buffer to the serial port\n");
105 bResult
= WriteFile(hPort
, txBuffer
, BUFSIZE
, &dwNumWritten
, NULL
);
107 printf("ERROR: failed to write to the serial port: %lx\n", (DWORD
)bResult
);
110 printf("WriteFile() returned: %lx, byteswritten: %lx\n", (DWORD
)bResult
, dwNumWritten
);
112 printf("Attempting to read %d bytes from the serial port\n", BUFSIZE
);
113 bResult
= ReadFile(hPort
, rxBuffer
, BUFSIZE
, &dwNumRead
, NULL
);
115 printf("ERROR: failed to read from the serial port: %lx\n", (DWORD
)bResult
);
118 printf("ReadFile() returned: %lx, bytesread: %lx\n", (DWORD
)bResult
, dwNumRead
);
119 for (i
= 0; i
< BUFSIZE
; i
++) {
120 printf(" %d ",rxBuffer
[i
]);
123 printf("Attempting to close the serial port\n");
124 bResult
= ClearCommError(hPort
, &dwErrors
, NULL
);
125 printf("ClearCommError returned: %lx, dwErrors: %lx\n", (DWORD
)bResult
, dwErrors
);
126 bResult
= CloseHandle(hPort
);
128 printf("ERROR: failed to close the serial port: %lx\n", (DWORD
)bResult
);
131 printf("Finished\n");