C++中检测串口是否可用
在系统通信中,经常会使用到串口通讯,因此对选择的串口是否可用很有必要进行检测,下面是关于串口检测的一段代码:
int CSerialPort::TestPort(int port)
{
volatile HANDLE temp=0;
CString szPort;
if(port > 100)
{
return FALSE;
}
//(注意:端口号大于9时,端口路径有变,这一块与底层驱动有关)
if(port < 10)
{
szPort.Format(_T("COM%d"),port);
}
else
{
szPort.Format(_T("\\\\.\\COM%d"),port);
}
//sprintf(szPort, "COM%d", portnr);
if (m_hComm != NULL && m_hComm != INVALID_HANDLE_VALUE)
{
return FALSE;
}
temp = CreateFile(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 (temp != NULL && temp != INVALID_HANDLE_VALUE)
{
CloseHandle(temp);
temp = NULL;
return TRUE;
}
else
{
return FALSE;
}
}