Qt遍历串口以及串口操作

一、添加串口模块

cmake中添加:

#添加SerialPort模块 下面整句添加
qt5_use_modules(${PROJECT_NAME} Core SerialPort)

或者

find_package(Qt5Core  COMPONENTS Qt5SerialPort REQUIRED)

二、遍历串口

#include <QtSerialPort/QSerialPort>//串口接口
#include <QtSerialPort/QSerialPortInfo>//串口接口信息

/**
 * @brief枚举出所有的串口,并寻找出指定描述Description的串口,比如NDI导航头的serialPortDescription可以在设备管理器中查看
 * NDI的serialPortDescription一般不会变,可用于自动识别串口
 *
*/
std::string NDICAPI::getSerialPortName(std::string serialPortDescription)
{
    std::string retPortName {};
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
       //通常通过串口名称进行连接,例COM1,所以在此处获取串口名称
//        qDebug() << "Name : " << info.portName();
//        qDebug() << "Description : " << info.description();
//        qDebug() << "Manufacturer: " << info.manufacturer();
//        qDebug() << "Serial Number: " << info.serialNumber();
//        qDebug() << "System Location: " << info.systemLocation()<<"\n";


        if(serialPortDescription == info.description().toStdString())
        {
            #ifdef _WIN32 // Windows serial port implementation
                retPortName = info.portName().toStdString();
            #else // Mac/Linux serial port implementation
                retPortName = info.systemLocation().toStdString();
            #endif
        }


    }


    if(retPortName == "")
    {
        qDebug() << "can not find SerialPortName,please check serialPortDescription";
        std::cout << "Press Enter to continue...";
        std::cin.ignore();
        exit(-1);
    }

    return retPortName;
}

三、参考链接:

https://blog.csdn.net/zusi_csdn/article/details/80976841

https://stackoverflow.com/questions/34128686/how-do-i-add-qserialport-module-into-cmake/34130985

四、Linux串口配置

https://blog.csdn.net/liudsl/article/details/79266003

注意:串口数据/t-/n的转换

    config.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    config.c_iflag &= ~(INLCR| ICRNL | IGNCR);
    config.c_cc[VMIN] = 0;                  /* use constant, not interval timout */
    config.c_cc[VTIME] =100/100; /* wait time is in 10ths of a second */

注意:清楚缓存区

    tcflush(fdComm_, TCIOFLUSH);
    tcflush(fdComm_, TCIFLUSH);
    tcflush(fdComm_, TCOFLUSH); /* clear input/output buffers */

链接:

https://blog.csdn.net/coobutter/article/details/17502367

https://www.cnblogs.com/zgq0/p/8078505.html

发布了142 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_38293453/article/details/104309298