1 #include <Windows.h>
2 #include <iostream>
3 #include <string>
4 #include <stdio.h>
5
6 using namespace std;
7 int main()
8 {
9
10 //全局变量,串口句柄
11 HANDLE hCom = CreateFile(L"COM3", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
12 if (hCom == (HANDLE)-1)
13 {
14 printf_s("打开COM失败!");
15 return FALSE;
16 }
17 else
18 {
19 SetupComm(hCom, 1024, 1024); //输入缓冲区和输出缓冲区的大小都是1024
20 COMMTIMEOUTS TimeOuts;
21 //设定读超时
22 TimeOuts.ReadIntervalTimeout = 1000;
23 TimeOuts.ReadTotalTimeoutMultiplier = 500;
24 TimeOuts.ReadTotalTimeoutConstant = 5000;
25 //设定写超时
26 TimeOuts.WriteTotalTimeoutMultiplier = 500;
27 TimeOuts.WriteTotalTimeoutConstant = 2000;
28 SetCommTimeouts(hCom, &TimeOuts); //设置超时
29
30 DCB dcb;
31 GetCommState(hCom, &dcb);
32 dcb.BaudRate = 115200; //波特率为9600
33 dcb.ByteSize = 8; //每个字节有8位
34 dcb.Parity = NOPARITY; //无奇偶校验位
35 dcb.StopBits = TWOSTOPBITS; //两个停止位
36 SetCommState(hCom, &dcb);
37
38 PurgeComm(hCom, PURGE_TXCLEAR | PURGE_RXCLEAR);
39 FILE* fd;
40 while (true)
41 {
42 //同步读串口
43 char str[256] = { 0x00 };
44 DWORD wCount;//读取的字节数
45 BOOL bReadStat;
46 bReadStat = ReadFile(hCom, str, sizeof(str), &wCount, NULL);
47 if (!bReadStat)
48 {
49 printf_s("读串口失败!");
50 return FALSE;
51 }
52 else
53 {
54 printf_s("%s\n", str);
55 fd = fopen("log.txt", "a+");
56 fwrite(str, sizeof(str), strlen(str), fd);
57 }
58 Sleep(100);
59 }
60 //fclose(fd);
61 }
62 system("pause");
63 return 0;
64 }