#define USBSERIAL_NAME "\\\\.\\wceusbsh001"
int _tmain(int argc, _TCHAR* argv[]) { HANDLE hSerial; DCB PortDCB; COMMTIMEOUTS CommTimeouts; unsigned char buf[64]; DWORD i, num; BOOL SerialFlag; hSerial = CreateFile(_T(USBSERIAL_NAME), (GENERIC_READ | GENERIC_WRITE), 0, NULL, OPEN_EXISTING, 0, NULL); if (hSerial == NULL) { printf("Open Error.\r\n"); return 1; }
PortDCB.DCBlength = sizeof(DCB); GetCommState(hSerial, &PortDCB); PortDCB.BaudRate = 115200; PortDCB.ByteSize = 8; PortDCB.Parity = NOPARITY; PortDCB.StopBits = ONESTOPBIT; if (! SetCommState(hSerial, &PortDCB)) { printf("Set COM Parameter Error.\r\n"); CloseHandle(hSerial); return 1; }
GetCommTimeouts(hSerial, &CommTimeouts); CommTimeouts.ReadIntervalTimeout = MAXDWORD; CommTimeouts.ReadTotalTimeoutMultiplier = 10; CommTimeouts.ReadTotalTimeoutConstant = 10; CommTimeouts.WriteTotalTimeoutMultiplier = 50; CommTimeouts.WriteTotalTimeoutConstant = 100;
if (!SetCommTimeouts(hSerial, &CommTimeouts)) { printf("Set COM timeout parameter error.\r\n"); CloseHandle(hSerial); return 1; } // Write data
for (i = 0; i < 10; i ++) { memset(buf, i, sizeof(buf)); SerialFlag = WriteFile(hSerial, buf, sizeof(buf), &num, NULL); if (SerialFlag) { printf("Write %d bytes to COM.\r\n", num); } else { printf("Write COM Error.\r\n"); } Sleep(1000); }
// Receive Data
while(1) { memset(buf, 0, sizeof(buf)); SerialFlag = ReadFile(hSerial, buf, 16, &num, 0); if (SerialFlag) { if (num == 0) { printf("Read Successfully, but didn't read any data.\r\n"); } else { printf("Read data: "); for (i = 0; i < 16; i ++) { printf("0x%x, ", buf[i]); } printf("\r\n"); } } else { printf("Read COM Error.\r\n"); } Sleep(1000); }
CloseHandle(hSerial);
return 0; }
|