QT打开二进制文件(.bin),串口定时发送

本例由《qt开发环境 - 简易二进制文件打开,串口自发自收》更改来。(由qt官方terminal demo 修改)

实现功能:打开.bin文件,显示文件内容

          通过串口按固定字节大小发送文件

          显示串口收到的内容

下面是源代码:

代码下载地址:http://download.csdn.net/download/zn2857/10194028

/****************************************************************************
**
** Copyright (C) 2012 Denis Shienkov <denis.shienkov@gmail.com>
** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/#include "mainwindow.h"
#include "ui_mainwindow.h"
//#include "console.h"
#include "settingsdialog.h"#include <QMessageBox>
#include <QLabel>
#include <QtSerialPort/QSerialPort>#include <QFile>
#include <QFileDialog>
#include <QDir>
#include <QTextStream>
#include <QDataStream>
#include <QTimer>#define APP_DISPLAY_SIZE 64//! [0]
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{
//! [0]ui->setupUi(this);
//    console = new Console;
//    console->setEnabled(false);
//    setCentralWidget(console);
//! [1]serial = new QSerialPort(this);
//! [1]settings = new SettingsDialog;ui->actionConnect->setEnabled(true);ui->actionDisconnect->setEnabled(false);ui->actionQuit->setEnabled(true);ui->actionConfigure->setEnabled(true);status = new QLabel;ui->statusBar->addWidget(status);initActionsConnections();connect(serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error),this, &MainWindow::handleError);//! [2]connect(serial, &QSerialPort::readyRead, this, &MainWindow::readData);
//! [2]
//    connect(console, &Console::getData, this, &MainWindow::writeData);
//! [3]timer = new QTimer(this);connect(timer,SIGNAL(timeout()),this,SLOT(timerTransDate()));ulNum = 0;
//    timer->start(1000);
//    setCentralWidget(MainWindow);
}
//! [3]MainWindow::~MainWindow()
{delete settings;delete ui;
}//! [4]
void MainWindow::openSerialPort()
{SettingsDialog::Settings p = settings->settings();serial->setPortName(p.name);serial->setBaudRate(p.baudRate);serial->setDataBits(p.dataBits);serial->setParity(p.parity);serial->setStopBits(p.stopBits);serial->setFlowControl(p.flowControl);if (serial->open(QIODevice::ReadWrite)) {
//        console->setEnabled(true);
//        console->setLocalEchoEnabled(p.localEchoEnabled);ui->actionConnect->setEnabled(false);ui->actionDisconnect->setEnabled(true);ui->actionConfigure->setEnabled(false);showStatusMessage(tr("Connected to %1 : %2, %3, %4, %5, %6").arg(p.name).arg(p.stringBaudRate).arg(p.stringDataBits).arg(p.stringParity).arg(p.stringStopBits).arg(p.stringFlowControl));} else {QMessageBox::critical(this, tr("Error"), serial->errorString());showStatusMessage(tr("Open error"));}
}
//! [4]//! [5]
void MainWindow::closeSerialPort()
{if (serial->isOpen())serial->close();
//    console->setEnabled(false);ui->actionConnect->setEnabled(true);ui->actionDisconnect->setEnabled(false);ui->actionConfigure->setEnabled(true);showStatusMessage(tr("Disconnected"));
}
//! [5]void MainWindow::about()
{QMessageBox::about(this, tr("About Simple Terminal"),tr("The <b>Simple Terminal</b> example demonstrates how to ""use the Qt Serial Port module in modern GUI applications ""using Qt, with a menu bar, toolbars, and a status bar."));
}//! [6]
void MainWindow::writeData(const QByteArray &data)
{serial->write(data);
}
//! [6]//! [7]
void MainWindow::readData()
{
//    QByteArray data = serial->readAll();//    console->putData(data);QByteArray temp = serial->readAll();QString buf;if(!temp.isEmpty()){ui->textBrowser->setTextColor(Qt::black);
//                if(chrReceive->isChecked()){
//                    buf = temp;
//                }else if(hexReceive->isChecked()){for(int i = 0; i < temp.count(); i++){QString s;s.sprintf("%02X ", (unsigned char)temp.at(i));buf += s;}
//                }
//            ui->textBrowser->setText(ui->textBrowser->document()->toPlainText() + buf);ui->textBrowser->append(buf);QTextCursor cursor = ui->textBrowser->textCursor();cursor.movePosition(QTextCursor::End);ui->textBrowser->setTextCursor(cursor);ui->receivebyteLcdNumber->display(ui->receivebyteLcdNumber->value() + temp.size());
//            ui->statusBar->showMessage(tr("成功读取%1字节数据").arg(temp.size()));}}
//! [7]//! [8]
void MainWindow::handleError(QSerialPort::SerialPortError error)
{if (error == QSerialPort::ResourceError) {QMessageBox::critical(this, tr("Critical Error"), serial->errorString());closeSerialPort();}
}
//! [8]void MainWindow::initActionsConnections()
{connect(ui->actionConnect, &QAction::triggered, this, &MainWindow::openSerialPort);connect(ui->actionDisconnect, &QAction::triggered, this, &MainWindow::closeSerialPort);connect(ui->actionQuit, &QAction::triggered, this, &MainWindow::close);connect(ui->actionConfigure, &QAction::triggered, settings, &SettingsDialog::show);connect(ui->actionClear, &QAction::triggered, this, &MainWindow::clearTextBrowser);connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::about);connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
}void MainWindow::showStatusMessage(const QString &message)
{status->setText(message);
}void MainWindow::on_pushButton_clicked()
{timer->start(500);
}void MainWindow::clearTextBrowser()
{ui->textBrowser->setText(NULL);
}void MainWindow::on_openFileButton_clicked()
{//get file namefileName = QFileDialog::getOpenFileName(this,"Open File",QDir::currentPath());
//    qDebug()<< "fileName is" << fileName;ui->filePathLineEdit->setText (fileName);if(fileName.isEmpty()){QMessageBox::information(this,"Error Message", "Please Select a Text File");return;}QFileInfo *pcsfileInfo = new QFileInfo(fileName);binSize = pcsfileInfo->size ();QFile* file = new QFile;file->setFileName(fileName);bool ok = file->open(QIODevice::ReadOnly);if(ok){
//        QTextStream in(file);
//        ui->textEdit->setText(in.readAll());//read all context from the file}else{QMessageBox::information(this,"Error Message", "File Open Error" + file->errorString());return;}QDataStream in(file);char * binByte = new char[binSize];in.setVersion (QDataStream::Qt_5_9);ui->statusBar->showMessage(tr("准备读取数据"));in.readRawData (binByte, binSize);      //读出文件到缓存ui->statusBar->showMessage(tr("读取数据完毕"));tempByte = new QByteArray(binByte, binSize);                //格式转换QString *tempStr = new QString(tempByte->toHex ().toUpper ());//显示文件内容qint8 cnt = 1;qint16 kcnt = 0;for(qint64 i = 2; i < tempStr->size ();){tempStr->insert (i, ' ');//每个字节之间空一格i += 3;cnt++;if(cnt == 8)//每8个字节空2格{tempStr->insert (i, ' ');i += 1;}if(cnt == 16)//每16个字节空一格{cnt = 1;kcnt ++;if(kcnt == 64)//每64行,即1K数据,空一行{kcnt = 0;tempStr->insert (i, '\n');i++;}tempStr->insert (i, '\n');i += 3;         //避免换行后开头一个空格,换行相当于从新插入}}ui->statusBar->showMessage(tr("准备显示"));ui->fileViewPlainTextEdit->insertPlainText (*tempStr);ui->statusBar->showMessage(tr("显示完毕"));//    timer->start(1000);
//    serial->write(binByte,25);delete tempByte;delete[] binByte;delete tempStr;file->close ();delete file;
}
void MainWindow::timerTransDate()
{qint16 temp = 0;            //剩余待传数据qint16 FileSendEndFg;QFile *binFile = new QFile(fileName);binFile->open (QIODevice::ReadOnly);binFile->seek (ulNum * 1024);QDataStream in(binFile);char * binByte = new char[binSize];in.setVersion (QDataStream::Qt_5_9);in.readRawData (binByte, binSize);      //读出文件到缓存char * binLitByte = new char[64];//bin缓存static int binfileseek = 0;if(binfileseek > binSize){binfileseek = 0;timer->stop();return;}memcpy (binLitByte, binByte + binfileseek, 64);binfileseek += 64;temp = binSize - 1024*ulNum;serial->write(binLitByte,64);delete binByte;}


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/243521.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

VHDL操作符

VHDL操作符 省略操作符 一般的&#xff0c;为了简化表达和位数不定情况下的赋值&#xff0c;可使用短语&#xff08;OTHERS > X&#xff09;, 这是一个省略赋值操作符&#xff0c;它可以在较多位的位矢量赋值中做省略化的赋值&#xff0c;如有&#xff1a;SIGNAL d1 :STD_…

深圳当代艺术家的一次聚会

在深圳创意园的雅库酒吧参加了一次当代艺术家酒会。注意看两个舞者的鞋子。女的高跟鞋的粉红很别致好看&#xff0c;而那位仁兄的红色拖鞋&#xff0c;还有两截的裤子以及腰间的包包——哈。 现场。背景映出的交织纠葛的锁链&#xff0c;很有意味。 “革命女性的幸福高于一切”…

关于STM32的IAP与APP互相跳转

关于STM32的IAP与APP互相跳转 之前做了一个不带系统的IAP与APP互相跳转&#xff0c;在网上找了资料后&#xff0c;很顺畅就完成了&#xff0c;后来在IAR集成开发环境下&#xff0c;IAP无系统&#xff0c;APP用UCOS系统做互相跳转出现了很多问题。现将IAP学习过程和实际遇到问题…

进程中的信号赋值与变量赋值

进程中的信号赋值与变量赋值 比较对象信号SIGNAL变量VARIABLE基本用法用于作为电路的信号连线用于作为进程中局部数据存储单元适用范围在整个结构体内的任何地方都能适用只能在所定义的进程中使用行为特性在进程的最后才对信号赋值,有延时立即赋值,无延时与Verilog对比信号赋…

不安和怀疑,美丽而又危险:看两位80后女艺术家的展览

“由喻红策划”是北京尤伦斯艺术中心“由……策划”系列展览计划之一。策展人喻红是中央美术学院油画工作室的教授&#xff0c;是目前最著名的新生代女艺术家之一。本次参展的是两位1984和1986年出生的北京女艺术家潘琳和苑瑗&#xff0c;展览名称——物非物。 展览突出了两位艺…

win32程序测试键盘钩子

// Test_Hook.cpp : 定义控制台应用程序的入口点。 //#include "stdafx.h" #include <Windows.h> #include <stdio.h> #include <stdarg.h> #include <ctype.h> #include <WinError.h>// Some global variables HINSTANCE g_Instance;…

SOA的未解之谜

虽然围绕着SOA有数以千计的出版物、提供商和分析师的吹嘘&#xff0c;以及SOA曾被宣布死亡然后又在SOA宣言中重生的事实&#xff0c;但是该话题周围仍然存在许多疑团。McKendrick在他最新的一篇博文对此进行了讨论。\u0026#xD;\nSOA与云计算之间的区别&#xff1f;David Linthi…

状态机设计技术

状态机设计技术 就理论而言,任何时序模型都可以归结为一个状态机。 状态机的优势 (1)高效的过程控制模型。 (2)容易利用现成的EDA工具进行优化设计。 (3)系统性稳定。 (4)高速性能。 (5)高可靠性能。 VHDL状态机的一般结构 从信号输出方式分,有Mealy和Moore型两…

Linux文件系统目录结构

进入Linux根目录&#xff08;即“/”&#xff0c;Linux文件系统的入口&#xff0c;也是处于最高一级的目录&#xff09;&#xff0c;运行“ls–l”命令&#xff0c;看到Linux包含以下目录。1./bin包含基本命令&#xff0c;如ls、cp、mkdir等&#xff0c;这个目录中的文件都是可…

藉上帝之旨,行时代之命的文学长征

——张炜长篇小说《你在高原》阅读笔记 阅读张炜的小说我从来没有过陌生感&#xff0c;这种感觉正如卡尔维诺对经典作品的比喻。他说&#xff1a;“一部经典作品是一本即使初读也好像是在重温的书。”我读张炜的作品就是这种感受&#xff0c;舒展的过程如同一场对往事前尘的追忆…

SSE指令集

SSE指令集的介绍网上一大堆, 这里贴一个用VS2008环境下的SSE测试程序, 分别用C代码, C内联汇编, C的SSE Intrinsics三种方式计算卷积的程序...这是一个win32控制台程序..... 程序下载地址 : http://download.csdn.net/detail/hemmingway/4598506 主文件的代码一览: // Test_SSE…

书评“世界杯”

昨天晚上&#xff0c;手捧《哈扎尔词典》的米洛拉德帕维奇以1比0敲碎了君特格拉斯的《铁皮鼓》&#xff1b;斯拉沃热齐泽克拎着《伊拉克&#xff1a;借来的壶》2比2浇灭了贝侯赛因奥巴马的《我父亲的梦想》和他《无畏的希望》。 今天早上&#xff0c;0比0&#xff0c;史蒂文杰拉…

VHDL仿真流程

VHDL仿真流程 VHDL测试平台Test Bench的主要功能有4种 例化待验证的模块实体通过VHDL程序的行为描述,为待测模块实体提供激励信号收集待测模块实体的输出结果,必要时将该结果与预置的所期望的理想结果进行比较,并给出报告根据比较结果自动判断模块的内部功能结构是否正确简…

实现ftoa与itoa

/********************************************************************************************* Name : 浮点型转字符* Brief : none* Input : str:字符串指针 num:浮点数 n:精度* Output : none* Return : none***************************************************…

Apache Nuvem将带来更多的开源云?

只要你过去几年没被困在荒岛上出不来&#xff0c;你就不可能不知道人们在云上所花费的巨大心力。无论你是否相信云将成为软件的一个“根本转变”&#xff0c;毋庸置疑的是未来几年将是云的世界。虽然现在谈很多标准还为时尚早&#xff0c;但我们开始看到在安全/识别及基本架构等…

两个C++毫秒级定时器

Win32控制台测试程序如下, 其中完整的程序代码下载是: http://download.csdn.net/detail/hemmingway/4600235 // Test_Time.cpp : 定义控制台应用程序的入口点。 //#include "stdafx.h" #include "Timer.h" #include "TimeCounter.h"#define N 1…

狼行天下:追寻狼迹内蒙生态行第二天(续1)

临近傍晚的乌力亚思太山谷。乱云中的敖包和写有藏经文的旗帜。 我搭的帐篷。别看很小&#xff0c;可以住两个人。 能够睡6个人的巨大的帐篷&#xff0c;需要几个人才可以搭建起来。 夕阳把草原染成了赤金色。 《时尚健康》的三条汉子裹挟了自己的美女。这片草地&#xff0c;这堆…

VHDL子程序

VHDL子程序 VHDL子程序(SUBPROGRAM)是一个VHDL程序模块,这个模块利用顺序语句来定义和完成算法,因此只能使用顺序语句。这一点与进程相似,所不同的是,子程序不能像进程那样可以从本结构体的并行语句或其他进程结构中直接读取信号值或者向信号赋值。 VHDL子程序与其他软件…

stm8因为固定中断向量表地址引发的一系列问题及其处理

转载&#xff1a;https://blog.csdn.net/chen244798611/article/details/51334489 因为之前写个stm32的IAP升级程序&#xff0c;所以我总结了做IAP升级的三个主要的难点&#xff1a; 1、如何设置中断向量&#xff0c;也就是说中断向量的重定向 2、如何配置程序的起始地址 3、…

《北京作家》2010年第2期,总第4期出版

《北京作家》2010年第2期&#xff0c;总第4期出版。 “名家新作”栏目推出的是著名作家张洁的最新短篇小说《一生太长了》&#xff0c;这篇小说最早发表于《人民文学》杂志社&#xff0c;是张洁非常特殊的小说之一。小说以狼为视角&#xff0c;叙述了狼在人类主宰的自然界的生存…