Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QSerialport send binary data



  • Dear all,

    I'm setting up a communication between my PC and embedded system. My PC needs to send certain data to the embedded system.

    Now when I send for example "START" with QSerialport it sends ASCII code. So there is a lot of traffic on the bus to say start to bus.

    To reduce this (unnessecairy) traffic, I would like to send the raw data. As start signal I would for example send 00010001 and nothing more.

    Is this possible? If yes how should I do this?
    Below is the code I use at the moment.

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QtSerialPort/QSerialPort>
    #include <QDebug>
    
    QSerialPort *serial;
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    
    {
        ui->setupUi(this);
        QWidget::setWindowTitle("SCOT - TSP -- Terex Sensor Programmer");
        QWidget::setWindowIcon(QIcon(":/new/rsc/img/TSP_ICON.ico"));
    
        QPixmap logPix(":/new/rsc/img/Sarens.png");
        ui->SarLogo_Label->setPixmap(logPix);
    
        serial = new QSerialPort(this);
        serial->setPortName("com6");
        serial->setBaudRate(QSerialPort::Baud38400);
        serial->setDataBits(QSerialPort::Data8);
        serial->setParity(QSerialPort::NoParity);
        serial->setStopBits(QSerialPort::OneStop);
        serial->setFlowControl(QSerialPort::NoFlowControl);
        serial->open(QIODevice::ReadWrite);
        connect(serial,SIGNAL(readyRead()),this,SLOT(serialReceived()));
    }
    MainWindow::~MainWindow()
    {
        delete ui;
        serial->close();
    }
    
    
    void MainWindow::on_pushButton_clicked()
    {
        serial->write("START \n");
        qDebug()<<"START";
    }
    
    void MainWindow::serialReceived()
    {
        QByteArray ba;
        qDebug()<<ba;
        ba=serial->readAll();
        ui->Terminal_textedit->appendPlainText(ba);
    
    }
    
    void MainWindow::on_actionConnect_triggered()
    {
    
    }
    
    


  • @TMJJ001 said in QSerialport send binary data:

    qint64 QIODevice::write(const QByteArray &byteArray) (http://doc.qt.io/qt-5/qiodevice.html#write-2), for example, writes arbitrary binary bytes.


  • Qt Champions 2020

    Is this possible? If yes how should I do this?

    The '00010001' it is '0x11' in hexadecimal, so just write:

    serial.write(QByteArray::fromHex("11"));
    

    [offtop] I do not understand, what is hard for you? How do you program without knowing the basic knowledge, that goes in school? Why do you ask such questions without trying to find an answer in Google or in Qt documentation?[/offtop]


Log in to reply