1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
#include <windows.h>
#include <stdio.h>
// 修改为对应串口
#define SERIAL_NAME "\\\\.\\COM1"
// 修改为对应波特率
#define BAUD_RATE CBR_9600
#define BUF_SIZE 1024
/**
* 初始化串口配置信息
* @param hSerial
* @return
*/
int serialInit(HANDLE *hSerial) {
// 打开串口
*hSerial = CreateFile(SERIAL_NAME,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
0);
if (*hSerial == INVALID_HANDLE_VALUE) {
printf("Error opening serial port!\n");
return 0;
}
// 设置串口配置
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
GetCommState(*hSerial, &dcbSerialParams);
dcbSerialParams.BaudRate = BAUD_RATE;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
SetCommState(*hSerial, &dcbSerialParams);
// 清空串口
PurgeComm(*hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR);
// 设置超时
COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = 1000;
timeouts.ReadTotalTimeoutMultiplier = 1000;
timeouts.ReadTotalTimeoutConstant = 1000;
timeouts.WriteTotalTimeoutMultiplier = 1000;
timeouts.WriteTotalTimeoutConstant = 1000;
SetCommTimeouts(*hSerial, &timeouts);
return 1;
}
int main() {
HANDLE hSerial;
serialInit(&hSerial);
char buf[BUF_SIZE];
OVERLAPPED oRead;
oRead.Offset = 0;
oRead.OffsetHigh = 0;
oRead.hEvent = CreateEvent(0, 1, 0, 0);
BOOL fRead;
DWORD dwRead;
if (hSerial != INVALID_HANDLE_VALUE) {
fRead = ReadFile(hSerial, buf, BUF_SIZE, &dwRead, &oRead);
if (!fRead && GetLastError() == ERROR_IO_PENDING) {
// 等待异步操作完成
WaitForSingleObject(oRead.hEvent, INFINITE);
if (GetOverlappedResult(hSerial, &oRead, &dwRead, FALSE)) {
// 处理读取到的数据
buf[dwRead] = '\0'; // 确保字符串以null结尾
printf("Read %lu bytes: %s\n", dwRead, buf);
}
}
}
// 关闭串口
CloseHandle(oRead.hEvent);
CloseHandle(hSerial);
return 0;
}
|