69,382
社区成员
发帖
与我相关
我的任务
分享
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <windows.h>
#include <string.h>
#include <conio.h>
#include "tchar.h"
int main() {
HANDLE hCom1;
hCom1 = CreateFile(_T("COM1"),//COM1口
GENERIC_READ | GENERIC_WRITE,//允许读和写
0,//独占方式
NULL,
OPEN_EXISTING,//打开而不是创建
0,//同步方式
NULL);
if (hCom1 == (HANDLE)-1) {
printf("打开COM失败!\n");
return FALSE;
} else {
printf("COM打开成功!\n");
}
SetupComm(hCom1, 20480, 20480);//输入缓冲区和输出缓冲区的大小都是1024
COMMTIMEOUTS TimeOuts;
//设定读超时
TimeOuts.ReadIntervalTimeout = 1000;
TimeOuts.ReadTotalTimeoutMultiplier = 500;
TimeOuts.ReadTotalTimeoutConstant = 5000;
//设定写超时
TimeOuts.WriteTotalTimeoutMultiplier = 500;
TimeOuts.WriteTotalTimeoutConstant = 2000;
SetCommTimeouts(hCom1, &TimeOuts);//设置超时
DCB dcb1;
GetCommState(hCom1, &dcb1);
dcb1.BaudRate = 115200;//波特率为9600
dcb1.ByteSize = 8;//每个字节有8位
dcb1.Parity = NOPARITY;//无奇偶校验位
dcb1.StopBits = TWOSTOPBITS;//两个停止位
dcb1.fParity = FALSE;
dcb1.fNull = FALSE;
SetCommState(hCom1, &dcb1);
DWORD wCount,n;//读取的字节数
FILE *fp1;
fp1 = fopen("串口发送的数据11.txt", "a+");
unsigned char str[8];
// PurgeComm(hCom1, PURGE_TXCLEAR | PURGE_RXCLEAR);//清空缓冲区
n=0;
while (1) {
wCount=8;
if (!ReadFile(hCom1, str, wCount, &wCount, NULL)) {
printf("读串口失败!");
break;
}
for (i = 0; i < wCount; i++) {
fprintf(fp1, "%02X ", str[i]);
printf("%02X ",str[i]);
if (n%16==0) printf("\n %08X - ",n);
if (n%320==0) system("cls");
n++;
printf("%02X ",str[i]);
}
fflush(fp1);
}
fclose(fp1);
CloseHandle(hCom1);
}