[toc]

用C语言在windows中使用串口通信

  • 接收串口消息的时候,如果出现乱码将串口速率修改到正确速率。

UART.c

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
89
//UART.c
#include <windows.h>
#include <stdio.h>

#define COM_PORT "COM3" // 串口号(根据实际情况修改)
#define BAUD_RATE 115200 // 波特率

/* 发送数据 */
void send_data(HANDLE hSerial, const char* data) {
DWORD bytesWritten;
if (!WriteFile(hSerial, data, strlen(data), &bytesWritten, NULL)) {
printf("发送失败\n");
}
else {
printf("发送成功: %s\n", data);
}
}

/* 读取串口数据 */
void read_data(HANDLE hSerial) {
char buffer[256] = { 0 };
DWORD bytesRead;

while (1) { // 循环读取数据
if (ReadFile(hSerial, buffer, sizeof(buffer) - 1, &bytesRead, NULL) && bytesRead > 0) {
buffer[bytesRead] = '\0';
printf("接收: %s\n", buffer);
}
Sleep(100); // 避免 CPU 过载
}
}

/* 主函数 */
int main() {
HANDLE hSerial;
DCB dcbSerialParams = { 0 };
COMMTIMEOUTS timeouts = { 0 };

/* 打开串口 */
hSerial = CreateFileA(COM_PORT, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hSerial == INVALID_HANDLE_VALUE) {
printf("无法打开串口 %s\n", COM_PORT);
return 1;
}
printf("成功打开串口 %s\n", COM_PORT);

/* 配置串口 */
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams)) {
printf("获取串口状态失败\n");
return 1;
}
dcbSerialParams.BaudRate = BAUD_RATE;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.Parity = NOPARITY;
dcbSerialParams.StopBits = ONESTOPBIT;
if (!SetCommState(hSerial, &dcbSerialParams)) {
printf("设置串口参数失败\n");
return 1;
}

/* 设置超时 */
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
SetCommTimeouts(hSerial, &timeouts);

/* 启动读取线程 */
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)read_data, hSerial, 0, NULL);

/* 发送数据 */
char input[256];
while (1) {
printf("输入要发送的数据: ");
fgets(input, sizeof(input), stdin);

if (input[0] == 'q') break; // 输入 'q' 退出

send_data(hSerial, input);
}

/* 关闭串口 */
CloseHandle(hSerial);
printf("串口关闭\n");
return 0;
}