Debian Codegraph @

test/commw32/commw32.c

raw symbols SCIP
1 // Copyright 2014 Quoc-Viet Nguyen. All rights reserved.
2 // This software may be modified and distributed under the terms
3 // of the BSD license. See the LICENSE file for details.
4
5 // Test serial communication in Win32
6 // gcc commw32.c
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 // No software handshaking
52 dcb.fTXContinueOnXoff = 1;
53 dcb.fOutX = 0;
54 dcb.fInX = 0;
55 // Binary mode
56 dcb.fBinary = 1;
57 // No blocking on errors
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 // time-out between charactor for receiving (ms)
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 }