|
@@ -0,0 +1,81 @@
|
|
1
|
+/*
|
|
2
|
+ * Windows 16 (& 32 & 64?) compatible serial port library
|
|
3
|
+ * Uses 8 databits, no parity, 1 stop bit, no handshaking
|
|
4
|
+ * By: Thomas Buck <taucher.bodensee@gmail.com>
|
|
5
|
+ * Visit: www.xythobuz.org
|
|
6
|
+ */
|
|
7
|
+
|
|
8
|
+#include <stdio.h>
|
|
9
|
+#include <windows.h>
|
|
10
|
+
|
|
11
|
+#define BAUD CBR_19200;
|
|
12
|
+
|
|
13
|
+HANDLE hSerial = INVALID_HANDLE_VALUE;
|
|
14
|
+
|
|
15
|
+// Open the serial port
|
|
16
|
+int serialOpen(char *port) {
|
|
17
|
+ DCB dcbSerialParams = {0};
|
|
18
|
+ COMMTIMEOUTS timeouts = {0};
|
|
19
|
+
|
|
20
|
+ hSerial = CreateFile(port GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
|
|
21
|
+
|
|
22
|
+ if (hSerial == INVALID_HANDLE_VALUE) {
|
|
23
|
+ return -1;
|
|
24
|
+ }
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+ dcbSerial.DCBlength = sizeof(dcbSerialParams);
|
|
28
|
+ if (!GetCommState(hSerial, &dcbSerialParams)) {
|
|
29
|
+ CloseHandle(hSerial);
|
|
30
|
+ hSerial = INVALID_HANDLE_VALUE;
|
|
31
|
+ return -1;
|
|
32
|
+ }
|
|
33
|
+ dcbSerialParams.BaudRate = BAUD;
|
|
34
|
+ dcbSerialParams.ByteSize = 8;
|
|
35
|
+ dcbSerialParams.StopBits = ONESTOPBIT;
|
|
36
|
+ dcbSerialParams.Parity = NOPARITY;
|
|
37
|
+ if (!SetCommState(hSerial, &dcbSerialParams)) {
|
|
38
|
+ CloseHandle(hSerial);
|
|
39
|
+ hSerial = INVALID_HANDLE_VALUE;
|
|
40
|
+ return -1;
|
|
41
|
+ }
|
|
42
|
+
|
|
43
|
+ timeouts.ReadIntervalTimeout = 50;
|
|
44
|
+ timeouts.ReadTotalTimeoutConstant = 50;
|
|
45
|
+ timeouts.ReadTotalTimeoutMultiplier = 10;
|
|
46
|
+ timeouts.WriteTotalTimeoutConstant = 50;
|
|
47
|
+ timeouts.WriteTotalTimeoutMultiplier = 10;
|
|
48
|
+
|
|
49
|
+ if (!SetCommTimeouts(hSerial, &timeouts)) {
|
|
50
|
+ CloseHandle(hSerial);
|
|
51
|
+ hSerial = INVALID_HANDLE_VALUE;
|
|
52
|
+ return -1;
|
|
53
|
+ }
|
|
54
|
+
|
|
55
|
+ return 0;
|
|
56
|
+}
|
|
57
|
+
|
|
58
|
+// Write to port. Returns number of characters sent, -1 on error
|
|
59
|
+ssize_t serialWrite(char *data, size_t length) {
|
|
60
|
+ DWORD dwBytesWritten = 0;
|
|
61
|
+ if (!WriteFile(hSerial, data, length, &dwBytesWritten, NULL)) {
|
|
62
|
+ return -1;
|
|
63
|
+ }
|
|
64
|
+ return dwBytesWritten;
|
|
65
|
+
|
|
66
|
+}
|
|
67
|
+
|
|
68
|
+// Read from port. Return number of characters read, 0 if none available, -1 on error
|
|
69
|
+ssize_t serialRead(char *data, size_t length) {
|
|
70
|
+ DWORD dwBytesRead = 0;
|
|
71
|
+ if (!ReadFile(hSerial, data, length, &dwBytesRead, NULL)) {
|
|
72
|
+ return -1;
|
|
73
|
+ }
|
|
74
|
+ return dwBytesRead;
|
|
75
|
+}
|
|
76
|
+
|
|
77
|
+// Close the serial Port
|
|
78
|
+void serialClose(void) {
|
|
79
|
+ CloseHandle(hSerial);
|
|
80
|
+ hSerial = INVALID_HANDLE_VALUE;
|
|
81
|
+}
|