串口打开失败 VS2010

C++语言 码拜 8年前 (2016-04-15) 1299次浏览
在网上下载了一个CSerialPort类,然后用VS2010创建了一个基于MFC的工程,发现打开串口就是不灵,用GetLastError()返回是2,但是用串口调试工具试是好的……工程属性选择了Unicode,麻烦诸位高手帮看看怎么回事
这个是调用部分

void CSerialPortDemoDlg::OnBnClickedButton1()
{
	// TODO: Add your control notification handler code here
	bool bStauts;
	TCHAR str[256] = {};
	int i = m_cmbCom.GetCurSel() + 1;
	bStauts = CSPort.InitPort(this,i,19200,"N",8,1,9,512,1000,1000,1000,1000,1000);
	if (bStauts)
	{
		MessageBoxW(str,_T("端口正确"));
	}
	else
	{
	    MessageBoxW(str,_T("端口错误"));
	}

这个是InitPort的部分

sprintf(szBaud, "baud=%d parity=%c data=%d stop=%d", baud, parity, databits, mystop);
	// get a handle to the port
	m_hComm = CreateFile((LPCWSTR)szPort,						// communication port string (COMX)
						 GENERIC_READ | GENERIC_WRITE,	// read/write types
						 0,								// comm devices must be opened with exclusive access
						 NULL,							// no security attributes
						 OPEN_EXISTING,					// comm devices must use OPEN_EXISTING
						 FILE_FLAG_OVERLAPPED,			// Async I/O
						 0);							// template must be 0 for comm devices
	if (m_hComm == INVALID_HANDLE_VALUE)
	{
		 INT err = GetLastError();
		// port not found
		delete [] szPort;
		delete [] szBaud;
		return FALSE;
	}
解决方案

20

GetLastError()返回的2可能是个枚举值或宏,你追进去看看对应的是什么。
CreateFile是类库中打开串口的方法吗?很有趣的是他为什么这样命名呢…

20

                    printf("请输入COM口(1):");
                    gets(temp);
                    if (*temp)
                        sprintf(port,"\\.\COM%d",atoi(temp));
                    else
                        strcpy(port,"\\.\COM1");

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明串口打开失败 VS2010
喜欢 (0)
[1034331897@qq.com]
分享 (0)