用API函数作串口通讯,如果串口号大于10,比如COM13,就无法打开串口,请问这是什么原因?如何解决?

luchang 2005-08-26 03:27:00
如题
...全文
210 点赞 收藏 4
写回复
4 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
legendhui 2005-08-26
小于10时候加不加都行的,大于9时候就是必须要加"\\\\.\\"

比如串口10,对应的参数为"\\\\.\\COM10",
回复
legendhui 2005-08-26
void CLSComm::Initialize(UINT uBaud, char chParity, UINT uDataBits, float fStopBits)
{
m_uBaudRate= uBaud;
m_chParity= chParity;
m_uDataBits= uDataBits;

if (fStopBits == 1.5)// 1.5 个停止位
m_uStopBits= 2;
else if(fStopBits > 1.5)// 2 个停止位
m_uStopBits= 3;
else
m_uStopBits= 1;// 1 个停止位
}

BOOL CLSComm::OpenDevice(UINT uPort, HWND hMsgTarget)
{
BOOLbResult = FALSE;
TCHARszPort[MAX_PATH];
TCHARszBaud[MAX_PATH];

m_uCommPort= uPort;
m_hTargetWindow= hMsgTarget;

CloseDevice();

m_hWriteEvent= CreateEvent(NULL, TRUE, FALSE, NULL);// 发送数据事件
m_hShutdownEvent= CreateEvent(NULL, TRUE, FALSE, NULL);// 关闭线程的事件
m_ovComm.hEvent= CreateEvent(NULL, TRUE, FALSE, NULL);// 读取数据事件

m_hEventArray[USER_EVENT_QUIT]= m_hShutdownEvent;
m_hEventArray[USER_EVENT_RECEIVE]= m_ovComm.hEvent;
m_hEventArray[USER_EVENT_SEND]= m_hWriteEvent;

wsprintf(szPort, _T("\\\\.\\COM%d"), m_uCommPort);
wsprintf(szBaud, _T("baud=%d parity=%c data=%d stop=%d"), m_uBaudRate, m_chParity, m_uDataBits, m_uStopBits);

InitializeCriticalSection(&m_csCritical);
EnterCriticalSection(&m_csCritical);

// 打开串口设备
m_hDevice = CreateFile(szPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
if (m_hDevice == INVALID_HANDLE_VALUE)
{
m_hDevice = NULL;
return FALSE;
}

if (SetCommTimeouts(m_hDevice, &m_timeoutComm))
{
if (SetCommMask(m_hDevice, EV_RXCHAR | EV_TXEMPTY | EV_CTS))
{
if (GetCommState(m_hDevice, &m_dcbComm))
{
m_dcbComm.fRtsControl = RTS_CONTROL_ENABLE;
//m_dcbComm.fRtsControl = RTS_CONTROL_DISABLE;
//m_dcbComm.fDtrControl = DTR_CONTROL_ENABLE;
if (BuildCommDCB(szBaud, &m_dcbComm))
{
if (SetCommState(m_hDevice, &m_dcbComm))
{
PurgeComm(m_hDevice, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
m_hCommThread = CreateThread(NULL, 0, _CommThread, this, 0, &m_dwCommThreadID);
bResult = (m_hCommThread != NULL) ? TRUE : FALSE;
}
}
}
}
}

LeaveCriticalSection(&m_csCritical);

if (!bResult)
CloseDevice();
else
m_bThreadAlive = TRUE;

return bResult;
}
回复
CreateFile ("\\\\.\\COM13",...);
回复
masterz 2005-08-26
GetLastError()
//check error message
#include <windows.h>

void ErrorExit(LPTSTR lpszFunction)
{
TCHAR szBuf[80];
LPVOID lpMsgBuf;
DWORD dw = GetLastError();

FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );

wsprintf(szBuf,
"%s failed with error %d: %s",
lpszFunction, dw, lpMsgBuf);

MessageBox(NULL, szBuf, "Error", MB_OK);

LocalFree(lpMsgBuf);
ExitProcess(dw);
}

回复
相关推荐
发帖
网络编程
创建于2007-09-28

1.8w+

社区成员

VC/MFC 网络编程
申请成为版主
帖子事件
创建了帖子
2005-08-26 03:27
社区公告
暂无公告