| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
#include <stdlib.h> |
| 8 |
#include <stdio.h> |
| 9 |
#include <windows.h> |
| 10 |
|
| 11 |
static const char* port = "COM4"; |
| 12 |
|
| 13 |
static printLastError() { |
| 14 |
char lpBuffer[256] = "?"; |
| 15 |
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, |
| 16 |
NULL, |
| 17 |
GetLastError(), |
| 18 |
MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), |
| 19 |
lpBuffer, |
| 20 |
sizeof(lpBuffer)-1, |
| 21 |
NULL); |
| 22 |
printf("%s\n", lpBuffer); |
| 23 |
} |
| 24 |
|
| 25 |
int main(int argc, char** argv) { |
| 26 |
HANDLE handle; |
| 27 |
DCB dcb = {0}; |
| 28 |
COMMTIMEOUTS timeouts; |
| 29 |
DWORD n = 0; |
| 30 |
char data[512]; |
| 31 |
int i = 0; |
| 32 |
|
| 33 |
handle = CreateFile(port, |
| 34 |
GENERIC_READ | GENERIC_WRITE, |
| 35 |
0, |
| 36 |
0, |
| 37 |
OPEN_EXISTING, |
| 38 |
0, |
| 39 |
0); |
| 40 |
if (handle == INVALID_HANDLE_VALUE) { |
| 41 |
printf("invalid handle %d\n", GetLastError()); |
| 42 |
printLastError(); |
| 43 |
return 1; |
| 44 |
} |
| 45 |
printf("handle created %d\n", handle); |
| 46 |
|
| 47 |
dcb.BaudRate = CBR_9600; |
| 48 |
dcb.ByteSize = 8; |
| 49 |
dcb.StopBits = ONESTOPBIT; |
| 50 |
dcb.Parity = NOPARITY; |
| 51 |
|
| 52 |
dcb.fTXContinueOnXoff = 1; |
| 53 |
dcb.fOutX = 0; |
| 54 |
dcb.fInX = 0; |
| 55 |
|
| 56 |
dcb.fBinary = 1; |
| 57 |
|
| 58 |
dcb.fAbortOnError = 0; |
| 59 |
|
| 60 |
if (!SetCommState(handle, &dcb)) { |
| 61 |
printf("set comm state error %d\n", GetLastError()); |
| 62 |
printLastError(); |
| 63 |
CloseHandle(handle); |
| 64 |
return 1; |
| 65 |
} |
| 66 |
printf("set comm state succeed\n"); |
| 67 |
|
| 68 |
|
| 69 |
timeouts.ReadIntervalTimeout = 1000; |
| 70 |
timeouts.ReadTotalTimeoutMultiplier = 0; |
| 71 |
timeouts.ReadTotalTimeoutConstant = 1000; |
| 72 |
timeouts.WriteTotalTimeoutMultiplier = 0; |
| 73 |
timeouts.WriteTotalTimeoutConstant = 1000; |
| 74 |
if (!SetCommTimeouts(handle, &timeouts)) { |
| 75 |
printf("set comm timeouts error %d\n", GetLastError()); |
| 76 |
printLastError(); |
| 77 |
CloseHandle(handle); |
| 78 |
return 1; |
| 79 |
} |
| 80 |
printf("set comm timeouts succeed\n"); |
| 81 |
|
| 82 |
if (!WriteFile(handle, "abc", 3, &n, NULL)) { |
| 83 |
printf("write file error %d\n", GetLastError()); |
| 84 |
printLastError(); |
| 85 |
CloseHandle(handle); |
| 86 |
return 1; |
| 87 |
} |
| 88 |
printf("write file succeed\n"); |
| 89 |
printf("Press Enter when ready for reading..."); |
| 90 |
getchar(); |
| 91 |
|
| 92 |
if (!ReadFile(handle, data, sizeof(data), &n, NULL)) { |
| 93 |
printf("read file error %d\n", GetLastError()); |
| 94 |
printLastError(); |
| 95 |
CloseHandle(handle); |
| 96 |
return 1; |
| 97 |
} |
| 98 |
printf("received data %d:\n", n); |
| 99 |
for (i = 0; i < n; ++i) { |
| 100 |
printf("%02x", data[i]); |
| 101 |
} |
| 102 |
printf("\n"); |
| 103 |
|
| 104 |
CloseHandle(handle); |
| 105 |
printf("closed\n"); |
| 106 |
return 0; |
| 107 |
} |