windows下C語言版串列埠接收程式(基於VS2017)
#include "pch.h"
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <string.h>
#include <conio.h>
#include "tchar.h"
int main()
{
HANDLE hCom;
hCom = CreateFile(_T("COM2"),//COM2口
GENERIC_READ | GENERIC_WRITE,//允許讀和寫
0,//獨佔方式
NULL,
OPEN_EXISTING,//開啟而不是建立
0,//同步方式
NULL);
if(hCom == (HANDLE)-1)
{
printf("開啟COM失敗!\n");
return FALSE;
}
else
{
printf("COM開啟成功!\n");
}
SetupComm(hCom, 20480, 20480);//輸入緩衝區和輸出緩衝區的大小都是1024
COMMTIMEOUTS TimeOuts;//設定讀超時
TimeOuts.ReadIntervalTimeout = 100;
TimeOuts.ReadTotalTimeoutMultiplier = 500;
TimeOuts.ReadTotalTimeoutConstant = 5000;
TimeOuts.WriteTotalTimeoutMultiplier = 500;//設定寫超時
TimeOuts.WriteTotalTimeoutConstant = 2000;
SetCommTimeouts(hCom, &TimeOuts);//設定超時
DCB dcb1;
GetCommState(hCom, &dcb1);
dcb1.BaudRate = 115200;//波特率為9600
dcb1.ByteSize = 8;//每個位元組有8位
dcb1.Parity = NOPARITY;//無奇偶校驗位
dcb1.StopBits = TWOSTOPBITS;//兩個停止位
dcb1.fParity = FALSE;
dcb1.fNull = FALSE;
SetCommState(hCom, &dcb1);
DWORD wCount = 256;//讀取的位元組數
DWORD wCount1;
PurgeComm(hCom, PURGE_TXCLEAR|PURGE_RXCLEAR);//清空緩衝區
while(1)
{
int i = 0;
FILE *fp1;
unsigned char str[256];
if(!ReadFile(hCom, str, wCount, &wCount1, NULL))
{
printf("讀串列埠失敗!");
return FALSE;
}
fp1 = fopen("串列埠傳送的數.txt", "a+");
if(wCount1 > 0)
{
printf("wCount1:%d\n", wCount1);
}
printf("讀串列埠成功!讀取資料為:\n");
for(i=0; i< wCount1; i++)
{
printf("%02X ", str[i]);
fprintf(fp1, "%02X ", str[i]);
}
printf("\n");
fclose(fp1);
}
CloseHandle(hCom);
std::cout << "Hello World!\n";
return 0;
}
執行效果:
配套VS2017工程下載地址:https://download.csdn.net/download/qinrenzhi/10774394