Qt 5.1 下实现串口通信

来源:互联网 发布:windows ce6.0模拟器 编辑:程序博客网 时间:2024/06/06 23:40
// reference the code source in :
http://www.pudn.com/downloads575/sourcecode/windows/other/detail2360461.html 
// the code upper is in linux platform
// I just change the file posix_qextserialport.cpp and it's .h file to win_qextserialport.cpp and .h respectively.
// Author: zeng bowei
// Date:   20150922
// Much thanks for the original developer of the main files about serial port.

修改中可能遇到qdatetime.h中的min()缺少参数的问题,可以在网上直接搜索到解决方法。
我的解决方法是:XXXXX.min()改为,(XXXXX.min)()这样就可以了
具体参考: http://jingyan.baidu.com/article/59a015e3438564f795886561.html 

还可能遇到没有.toASCII()这个函数,可以用.toLatin1()这个函数替代,表示将数据转换成ascii格式,如果要显示或发送为hex格式是数据,需要做转换,其中显示为hex格式的文件,可以将接受到的数据直接转换成hex,使用.toHex(),发送这要麻烦一些,需要将两个ascii转换成一个hex,再发送,具体代码如下:
void MainWindow::readMyCOM()
{
    // read all data in serial port's buffer
    QByteArray temp = myCOM->readAll();
    // display data in the textBrowser
    if(!ui->HexDisplayCheckBox->checkState()) // hex display not select, in ascii
          ui->textBrowser->insertPlainText(temp); // in ascii
    else // select
        ui->textBrowser->insertPlainText(temp.toHex()); // in hex
}

void MainWindow::on_sendMsgBtn_clicked()
{
    // send data to device in the form of ascii
    if(!ui->HexSendCheckBox->checkState()) // no select, in ascii
         myCOM->write(ui->sendMsgLineEdit->text().toLatin1());
    else // in hex
    {
        QByteArray a;
        QString temp1 = ui->sendMsgLineEdit->text(); // get the msg to temp1
        bool b = true;
        for( int i=0; i<temp1.length(); i+=2) // one hex = two ascii
            a.append(((temp1.mid(i,2)).toInt(&b, 16)));
        myCOM->write(a);
    }
}
0 0