#include "tchar.h"
#include int main()
{
/*****************************打开串口*************************************/
HANDLE hCom;//全局变量,串口句柄
hCom = CreateFile(_T("COM3"),//COM3口
GENERIC_READ | GENERIC_WRITE,//允许读和写
0,//独占方式
NULL,
OPEN_EXISTING,//打开而不是创建
0,//同步方式
//FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERAPPLE,//重叠方式
NULL);
if(hCom == (HANDLE)-1)
{
printf("打开COM失败!");
return 0;
}
/****************配置串口***************/
SetupComm(hCom, 20480, 20480);//输入缓冲区和输出缓冲区的大小都是20480
COMMTIMEOUTS TimeOuts;
TimeOuts.ReadIntervalTimeout = 1000;//设定读超时
TimeOuts.ReadTotalTimeoutMultiplier = 500;
TimeOuts.ReadTotalTimeoutConstant = 5000;
TimeOuts.WriteTotalTimeoutMultiplier = 500;//设定写超时
TimeOuts.WriteTotalTimeoutConstant = 2000;
SetCommTimeouts(hCom, &TimeOuts);//设置超时
DCB dcb;
GetCommState(hCom, &dcb);
dcb.BaudRate = 115200;//波特率为115200
dcb.ByteSize = 8;//每个字节有8位
dcb.Parity = NOPARITY;//无奇偶校验位
dcb.StopBits = TWOSTOPBITS;//两个停止位
dcb.fParity = FALSE;
dcb.fNull = FALSE;
SetCommState(hCom, &dcb);
PurgeComm(hCom, PURGE_TXCLEAR|PURGE_RXCLEAR);//在读写串口之前清空缓冲区
/********同步写串口********/
int i;
unsigned char sendData[256] = {0};//写入串口缓存区的数组
for(i=0; i<16; i++)
{
sendData[i] = i;
}
DWORD dwWriteLen = 0;
if(!WriteFile(hCom, sendData, 16, &dwWriteLen, NULL))
{
printf("串口发送数据失败!
");
}
printf("串口发送数据成功!
");
printf("发送的数据为:
");
for(i=0; i<16; i++)
{
printf("%02X ", sendData[i]);
}
printf("
");
/***********关闭串口***********/
CloseHandle(hCom);
std::cout << "Hello World!
";
return 0;
}
运行效果:
配套VS2017工程下载地址:https://download.csdn.net/download/qinrenzhi/10774388