Qt串口调试助手

如果大家以前搞过单片机,那么对串口调试助手一定不陌生。各种助手可以方便我们做一些测试、定位一些问题。今天和大家分享一下用Qt开发的跨平台串口调试助手。

先来一张效果图:

640?wx_fmt=png

其他串口调试助手:

640?wx_fmt=png

扫描二维码关注公众号,回复: 10304853 查看本文章

程序的主体构成:

PortSettings          类封装了串口的名称、波特率、数据位、校验位、

                      停止位和流控等一系列属性;

CommunicationThread   类在线程中接收和发送数据,防止数据量大的时候

                      阻塞主UI线程。

SerialPortMainWindow   UI类,设置串口通信属性、数据收发属性等。

重点说几个函数:

①主UI中打开串口

void SerialPortMainWindow::on_pbn_openSerialport_clicked()	
{	
    updatePortSettings();	

	
    if(!m_serialportStatus)	
    {	
        m_communicationThread = new CommunicationThread;	

	
      connect(m_communicationThread,SIGNAL(signal_serialportStatus(bool)),	
                this,SLOT(slot_serialportStatus(bool)));	

	
        connect(m_communicationThread,SIGNAL(signal_recvData(QByteArray)),	
                this,SLOT(slot_recvData(QByteArray)));	

	
        m_communicationThread->setSerialportParam(m_portSetting);	

	
        if(!m_communicationThread->isRunning())	
        {	
            m_communicationThread->start();	
        }	
    }	
    else	
    {	
        m_serialportStatus = false;	
        m_communicationThread->stopThread();	
        delete m_communicationThread;	
        m_communicationThread = NULL;	

	
        QIcon buttonIcon(":/myresources/Resources/led/open.png");	
        ui->pbn_openSerialport->setIcon(buttonIcon);	
        ui->pbn_openSerialport->setIconSize(QSize(130,40));	
    }	
}

打开/关闭串口,如果串口是关闭状态,则打开串口,反之则关闭串口。注意这里面没有检查是否有可用串口。如果有可用串口,则创建新的串口通信实例,建立相关信号和槽。

串口打开成功显示绿色的灯,是通过给按钮添加图标来实现的。

    这里提一下,Ascii与Hex的转换需要通过一个封装的函数实现。

②通信线程中的处理

void CommunicationThread::run()	
{	
    m_serialPort = new QSerialPort;	

	
    bool ret = m_serialPort->open(QIODevice::ReadWrite);	
    emit signal_serialportStatus(ret);	

	
    while(!m_quitThread && ret)	
    {	
        QByteArray readData = m_serialPort->readAll();	
        while (m_serialPort->waitForReadyRead(5))	
            readData += m_serialPort->readAll();	

	
        if(!readData.isEmpty())	
        {	
            emit signal_recvData(readData);	
        }	

	
        if(!m_sendDataQueue.isEmpty())	
        {	
            m_serialPort->write(m_sendDataQueue.dequeue());	
        }	
    }	
}

在run()中实例化m_serialPort,继承QThread重新实现run()函数,只有run()中的部分运行在线程中。主UI中如果要发送数据,则先让数据进入m_sendDataQueue队列中,m_serialPort再将队列中数据发送出去。使用readAll()读取数据,通过信号将数据发送出去。

Qt中线程间通讯可以使用信号和槽、队列等通讯方式。

Windows下为程序设置图标:

pro中添加  RC_FILE = Resources/serialIcon.rc

serialIcon.rc 中的内容: 

     IDI_ICON1  ICON DISCARDABLE  "icon/serialPortAssistant.ico"

    Ubuntu 下为程序设置桌面图标:

     具体方法可参见之前的文章。

/*******************************************************************/

     update:  20191217

     可添加自定波特率

       欢迎关注公众号:

关注公众号可后台留言获取源码,欢迎交流技术问题!

发布了91 篇原创文章 · 获赞 94 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/ACK_ACK/article/details/102674901