⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 myinitcomm.cpp

📁 vc下串口通讯开发程序
💻 CPP
字号:
#include "stdafx.h"
#include "myinitComm.h"
HANDLE InitComPort(COMM  comm)
{   HANDLE gComHandleProc = INVALID_HANDLE_VALUE;//NULL;

	DCB dcb;
	BOOL fSuccess = false;
		gComHandleProc = CreateFile(comm.comm,
			GENERIC_READ | GENERIC_WRITE,
			0,    // comm devices must be opened w/exclusive-access 
			NULL, // no security attributes 
			OPEN_EXISTING, // comm devices must use OPEN_EXISTING 
			0,    // not overlapped I/O 
			NULL  // hTemplate must be NULL for comm devices 
			);
	

	if (gComHandleProc == INVALID_HANDLE_VALUE) return gComHandleProc;

	SetCommMask(gComHandleProc,EV_CTS|EV_DSR);

	// Omit the call to SetupComm to use the default queue sizes.
	// Get the current configuration.

	fSuccess = GetCommState(gComHandleProc, &dcb);

	if (!fSuccess) 
	{
	EndComm(gComHandleProc);
		return INVALID_HANDLE_VALUE;
	}

	// Fill in the DCB: baud=1200, 8 data bits, no parity, 1 stop bit. 
/*
	dcb.BaudRate = 9600;
	dcb.ByteSize = 8;
	dcb.Parity = EVENPARITY;//NOPARITY;
	dcb.StopBits =ONESTOPBIT;// TWOSTOPBITS;//ONESTOPBIT;
	dcb.fRtsControl = 0;
*/

	dcb.BaudRate = comm.baut;
	dcb.ByteSize =comm.ByteSize;
	dcb.Parity = comm.Parity;//
	dcb.StopBits =comm.StopBits;
	dcb.fRtsControl = 0;

	fSuccess = SetCommState(gComHandleProc, &dcb);
	if(!fSuccess) 
	{
	EndComm(gComHandleProc);
		return INVALID_HANDLE_VALUE;
	}

	COMMTIMEOUTS cto;
	GetCommTimeouts(gComHandleProc, &cto);
	cto.ReadTotalTimeoutConstant	= 300;
	cto.ReadTotalTimeoutMultiplier	= 12000/dcb.BaudRate;
	fSuccess = SetCommTimeouts(gComHandleProc, &cto);
	if(!fSuccess) 
	{
	EndComm(gComHandleProc);
		return INVALID_HANDLE_VALUE;
	}
	return gComHandleProc;
}
void
EndComm(HANDLE gComHandleProc)
{
	if (gComHandleProc != INVALID_HANDLE_VALUE) 
	{
		CloseHandle(gComHandleProc);
		gComHandleProc = INVALID_HANDLE_VALUE;
	}
		
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -