嵌入式Linux的串口通讯C++程序设计(2)

// 设置线程绑定属性
        res = pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM );
        // 设置线程分离属性
        res += pthread_attr_setdetachstate( &attr, THREAD_CREATE_DETACHED );

ReceiveThreadFunc函数是串口数据接收和处理的主要核心代码,在该函数中调用select( ),阻塞等待串口数据的到来。对于接收到的数据处理也是在该函数中实现,在本例程中处理为简单的数据回发,用户可结合实际的应用修改此处代码,修改PackagePro( )函数即可。流程如下:

int CSerial::ReceiveThreadFunc(void* lparam)
        {
                CSerial *pSer = (CSerial*)lparam;

//定义读事件集合
                fd_set fdRead;
                int ret;
                struct timeval aTime;

while( 1 )
                {
                        //收到退出事件,结束线程
                        if( pSer->m_ExitThreadFlag )
                        {
                                break;
                        }
                        FD_ZERO(&fdRead);
                        FD_SET(pSer->m_fd,&fdRead);
                        aTime.tv_sec = 0;
                        aTime.tv_usec = 300000;
                        ret = select( pSer->m_fd+1,&fdRead,NULL,NULL,&aTime );
                        if (ret < 0 )
                        {
                                //关闭串口
                                pSer->ClosePort( );
                                break;
                        }
                        if (ret > 0)
                        {
                                //判断是否读事件
                                if (FD_ISSET(pSer->m_fd,&fdRead))
                                {
                                        //data available, so get it!
                                        pSer->m_DatLen = read( pSer->m_fd, pSer->DatBuf, 1500 );
                                        // 对接收的数据进行处理,这里为简单的数据回发
                                        if( pSer->m_DatLen > 0 )
                                        {
                                                pSer->PackagePro( pSer->DatBuf, pSer->m_DatLen);
                                        }
                                        // 处理完毕
                                }
                        }
                }
                printf( 'ReceiveThreadFunc finished\n');
                pthread_exit( NULL );
                return 0;
        }

需要注意的是,select( )函数中的时间参数在嵌入式Linux中每次都需要重新赋值,否则会自动归0。

CSerial类的实现代码请参见Serial.CPP文件。

CSerial类的调用

CSerial类的具体使用也比较简单,主要是对于类中定义的4个公共函数的调用,以下为 Step2_SerialTest.cpp中相关代码。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwssxd.html