UINT WINAPI CbintoarrayDlg::ListenThread(void* pParam)
{
/** 得到本类的指针 */
CbintoarrayDlg *pSerialPort = reinterpret_cast<CbintoarrayDlg*>(pParam);
// 线程循环,轮询方式读取串口数据
while (!pSerialPort->s_bExit)
{
UINT BytesInQue = pSerialPort->GetBytesInCOM();
/** 如果串口输入缓冲区中无数据,则休息一会再查询 */
if (BytesInQue == 0)
{
Sleep(SLEEP_TIME_INTERVAL);
continue;
}
/** 读取输入缓冲区中的数据并输出显示 */
unsigned char cRecved = 0x00;
int count = 0;
//memset(serildatabuf,0,sizeof(serildatabuf));
do
{
cRecved = 0x00;
if (pSerialPort->ReadChar(cRecved) == true)
{
serildatabuf[datacount++] = cRecved;
if(datacount >= 3){
if(datacount >= serildatabuf[2]){//接收完成, serildatabuf[2]为长度
memcpy(&Msgdatabuf[Msgdataindex],serildatabuf,datacount);
memset(serildatabuf,0,datacount);
Msgdataindex += datacount;//总长度
datacount =0;
Msgdatacnt++;//消息数目
}
}
continue;
}
} while (--BytesInQue);
//pSerialPort->DisplaySerilData(CString(serildatabuf));
}
return 0;
}
bool CbintoarrayDlg::OpenListenThread()
{
/** 检测线程是否已经开启了 */
if (m_hListenThread != INVALID_HANDLE_VALUE)
{
/** 线程已经开启 */
return false;
}
s_bExit = false;
/** 线程ID */
UINT threadId;
/** 开启串口数据监听线程 */
m_hListenThread = (HANDLE)_beginthreadex(NULL, 0,ListenThread, this, 0, &threadId);
if (!m_hListenThread)
{
return false;
}
/** 设置线程的优先级,高于普通线程 */
if (!SetThreadPriority(m_hListenThread, THREAD_PRIORITY_ABOVE_NORMAL))
{
return false;
}
return true;
}
这些函数也是百度到的,其实就两个函数,在initport 和openport之后调用OpenListenThread
ListenThread --监听过程
OpenListenThread--打开监听线程
接收数据过程中只用数组接收,不放打印之类的东西,会占用时间导致接收的数据丢失
所以应多建一个线程用来打印的