C++串口编程实例(三)
(2012-09-01 10:52:05)
标签:
串口默认值奇偶校验通信类通信协议杂谈 |
分类: CPP编程 |
-
-
if(m_hComm == INVALID_HANDLE_VALUE) -
{ -
LeaveCriticalSection(&m_csCommunicationSync); -
returnfalse; -
} -
-
-
LeaveCriticalSection(&m_csCommunicationSync); -
-
returntrue; -
}
-
- bool
CSerialPort::OpenListenThread() -
{
-
-
if(m_hListenThread != INVALID_HANDLE_VALUE) -
{ -
-
returnfalse; -
} -
-
false;s_bExit = -
-
UINTthreadId; -
-
HANDLE)_beginthreadex(NULL,m_hListenThread = ( 0, this,ListenThread, 0, &threadId); -
if(!m_hListenThread) -
{ -
returnfalse; -
} -
-
if(!SetThreadPriority(m_hListenThread, THREAD_PRIORITY_ABOVE_NORMAL)) -
{ -
returnfalse; -
} -
-
returntrue; -
}
-
-
bool
CSerialPort::CloseListenTread() -
{
-
if(m_hListenThread != INVALID_HANDLE_VALUE) -
{ -
-
true;s_bExit = -
-
-
Sleep(10); -
-
-
CloseHandle( m_hListenThread ); -
m_hListenThread = INVALID_HANDLE_VALUE; -
} -
returntrue; -
}
-
- UINT
CSerialPort::GetBytesInCOM() -
{
-
DWORDdwError = 0; -
COMSTAT comstat; -
sizeof(COMSTAT));memset(&comstat, 0, -
-
UINTBytesInQue = 0; -
-
if( ClearCommError(m_hComm, &dwError, &comstat) ) -
{ -
BytesInQue = comstat.cbInQue; -
} -
-
returnBytesInQue; -
}
-
- UINT
WINAPI void*CSerialPort::ListenThread( pParam ) -
{
-
-
reinterpret_cast<CSerialPort*>(pParam);CSerialPort *pSerialPort = -
-
//线程循环,轮询方式读取串口数据 -
while(!pSerialPort->s_bExit) -
{ -
UINTBytesInQue = pSerialPort->GetBytesInCOM(); -
-
if( BytesInQue == 0 ) -
{ -
Sleep(SLEEP_TIME_INTERVAL); -
continue; -
} -
-
-
charcRecved = 0x00; -
do -
{ -
cRecved = 0x00; -
if(pSerialPort->ReadChar(cRecved)== true) -
{ -
std::cout << cRecved ; -
continue; -
} -
while(--BytesInQue);} -
} -
return 0; -
}
-
- bool
CSerialPort::ReadChar( char&cRecved ) -
{
-
BOOLbResult = TRUE; -
DWORDBytesRead = 0; -
if(m_hComm== INVALID_HANDLE_VALUE) -
{ -
returnfalse; -
} -
-
-
EnterCriticalSection(&m_csCommunicationSync); -
-
-
bResult = ReadFile(m_hComm, &cRecved, 1, &BytesRead, NULL); -
if((!bResult)) -
{ -
-
DWORDdwError = GetLastError(); -
-
-
PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_RXABORT); -
LeaveCriticalSection(&m_csCommunicationSync); -
-
returnfalse; -
} -
-
-
LeaveCriticalSection(&m_csCommunicationSync); -
-
return(BytesRead == 1); -
}
-
-
bool
CSerialPort::WriteData( char*unsigned pData, intunsigned length ) -
{
-
BOOLbResult = TRUE; -
DWORDBytesToSend = 0; -
if(m_hComm== INVALID_HANDLE_VALUE) -
{ -
returnfalse; -
} -
-
-
EnterCriticalSection(&m_csCommunicationSync); -
-
-
bResult = WriteFile(m_hComm, pData, length, &BytesToSend, NULL); -
if(!bResult) -
{ -
DWORDdwError = GetLastError(); -
-
PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_RXABORT); -
LeaveCriticalSection(&m_csCommunicationSync); -
-
returnfalse; -
} -
-
-
LeaveCriticalSection(&m_csCommunicationSync); -
-
returntrue; - }
前一篇:C++串口编程实例(二)

加载中…