Search code examples
c++qtqtserialport

QByteArray to Double in Qt C++ 5.8.0


I have a serial comport data read write program. Data is being read from the comport 4 (Eg: 1022), but when I'm trying to do a mathematical calculation of the data 1022/2 then its give me output as 0.5 5.0 51.00 511.0 means its not taking the whole 1022 as a single number for the mathematical calculation. Its take 1 first then divide 1/2=0.5 then once 0 digit receive it take as 10/2=5 and so on. But I want 1022 as a single digit number like (eg: 1022/2=511)

I have tried to convert the QByteArray into Double for the calculation.

output

     void MainWindow::readData()
 {
     QByteArray data = serial->readAll();
     bool ok;
     QByteArray cata= QByteArray::number(data.toDouble(&ok)/2);

    console->putData(cata);
 }

Solution

  • So here an example of a TCP client/server in Qt. the server sends 1022.72, and the client receives it and shows the result value divided by 2. (run the server then the client:

    Server Code:

    test.pro:

    #-------------------------------------------------
    #
    # Project created by QtCreator 2017-06-26T12:49:54
    #
    #-------------------------------------------------
    
    QT       += core gui network
    
    greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
    
    TARGET = test
    TEMPLATE = app
    
    # The following define makes your compiler emit warnings if you use
    # any feature of Qt which as been marked as deprecated (the exact warnings
    # depend on your compiler). Please consult the documentation of the
    # deprecated API in order to know how to port your code away from it.
    DEFINES += QT_DEPRECATED_WARNINGS
    
    # You can also make your code fail to compile if you use deprecated APIs.
    # In order to do so, uncomment the following line.
    # You can also select to disable deprecated APIs only up to a certain version of Qt.
    #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
    
    
    SOURCES += main.cpp\
            mainwindow.cpp
    
    HEADERS  += mainwindow.h
    
    FORMS    += mainwindow.ui
    

    main.cpp:

    #include "mainwindow.h"
    #include <QApplication>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
    
        return a.exec();
    }
    

    mainwindow.cpp:

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    #include <QDebug>
    #include <QHostAddress>
    #include <QAbstractSocket>
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow),
        _server(this)
    {
        ui->setupUi(this);
        _server.listen(QHostAddress::Any, 4242);
        connect(&_server, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    
    }
    
    void MainWindow::onNewConnection()
    {
       QTcpSocket *clientSocket = _server.nextPendingConnection();
       connect(clientSocket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
       connect(clientSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));
    
        _sockets.push_back(clientSocket);
        for (QTcpSocket* socket : _sockets) {
            double data = 1022.72;
    //        socket->write(QByteArray::fromStdString(clientSocket->peerAddress().toString().toStdString() + " connected to server !\n"));
            socket->write(QByteArray::fromStdString(QVariant(data).toString().toStdString()));
        }
    }
    
    void MainWindow::onSocketStateChanged(QAbstractSocket::SocketState socketState)
    {
        if (socketState == QAbstractSocket::UnconnectedState)
        {
            QTcpSocket* sender = static_cast<QTcpSocket*>(QObject::sender());
            _sockets.removeOne(sender);
        }
    }
    
    void MainWindow::onReadyRead()
    {
        QTcpSocket* sender = static_cast<QTcpSocket*>(QObject::sender());
        QByteArray datas = sender->readAll();
        for (QTcpSocket* socket : _sockets) {
            if (socket != sender)
                socket->write(QByteArray::fromStdString(sender->peerAddress().toString().toStdString() + ": " + datas.toStdString()));
        }
    }
    

    mainwindow.h:

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    #include <QTcpServer>
    #include <QTcpSocket>
    
    namespace Ui {
    class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    public slots:
        void onNewConnection();
        void onSocketStateChanged(QAbstractSocket::SocketState socketState);
        void onReadyRead();
    private:
        Ui::MainWindow *ui;
        QTcpServer  _server;
        QList<QTcpSocket*>  _sockets;
    };
    
    #endif // MAINWINDOW_H
    

    mainwindow.ui: (empty)

    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
     <class>MainWindow</class>
     <widget class="QMainWindow" name="MainWindow">
      <property name="geometry">
       <rect>
        <x>0</x>
        <y>0</y>
        <width>400</width>
        <height>300</height>
       </rect>
      </property>
      <property name="windowTitle">
       <string>MainWindow</string>
      </property>
      <widget class="QWidget" name="centralWidget">
       <layout class="QVBoxLayout" name="verticalLayout_2">
        <item>
         <layout class="QVBoxLayout" name="verticalLayout"/>
        </item>
       </layout>
      </widget>
      <widget class="QMenuBar" name="menuBar">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>400</width>
         <height>25</height>
        </rect>
       </property>
      </widget>
      <widget class="QToolBar" name="mainToolBar">
       <attribute name="toolBarArea">
        <enum>TopToolBarArea</enum>
       </attribute>
       <attribute name="toolBarBreak">
        <bool>false</bool>
       </attribute>
      </widget>
      <widget class="QStatusBar" name="statusBar"/>
     </widget>
     <layoutdefault spacing="6" margin="11"/>
     <resources/>
     <connections/>
    </ui>
    

    Client code:

    test2.pro:

    #-------------------------------------------------
    #
    # Project created by QtCreator 2017-06-26T14:34:11
    #
    #-------------------------------------------------
    
    QT       += core gui network
    
    greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
    
    TARGET = test2
    TEMPLATE = app
    
    # The following define makes your compiler emit warnings if you use
    # any feature of Qt which as been marked as deprecated (the exact warnings
    # depend on your compiler). Please consult the documentation of the
    # deprecated API in order to know how to port your code away from it.
    DEFINES += QT_DEPRECATED_WARNINGS
    
    # You can also make your code fail to compile if you use deprecated APIs.
    # In order to do so, uncomment the following line.
    # You can also select to disable deprecated APIs only up to a certain version of Qt.
    #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
    
    
    SOURCES += main.cpp\
            mainwindow.cpp
    
    HEADERS  += mainwindow.h
    
    FORMS    += mainwindow.ui
    

    main.cpp:

    #include "mainwindow.h"
    #include <QApplication>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
    
        return a.exec();
    }
    

    mainwindow.cpp:

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    #include <QDebug>
    #include <QHostAddress>
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow),
        _socket(this)
    {
        ui->setupUi(this);
        _socket.connectToHost(QHostAddress("127.0.0.1"), 4242);
        connect(&_socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    void MainWindow::onReadyRead()
    {
        QByteArray datas = _socket.readAll();
    
        qDebug() << QVariant(datas).toDouble() / 2;
    
        ui->label->setText(QVariant(QVariant(datas).toDouble() / 2).toString());
    
        _socket.write(QByteArray("ok !\n"));
    }
    

    mainwindow.h:

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    #include <QTcpSocket>
    
    namespace Ui {
    class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    public slots:
        void onReadyRead();
    
    private:
        Ui::MainWindow *ui;
        QTcpSocket  _socket;
    };
    
    #endif // MAINWINDOW_H
    

    mainwindow.ui: (result written here and also with qDebug)

    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
     <class>MainWindow</class>
     <widget class="QMainWindow" name="MainWindow">
      <property name="geometry">
       <rect>
        <x>0</x>
        <y>0</y>
        <width>400</width>
        <height>300</height>
       </rect>
      </property>
      <property name="windowTitle">
       <string>MainWindow</string>
      </property>
      <widget class="QWidget" name="centralWidget">
       <layout class="QVBoxLayout" name="verticalLayout_2">
        <item>
         <layout class="QVBoxLayout" name="verticalLayout">
          <item>
           <widget class="QLabel" name="label">
            <property name="text">
             <string/>
            </property>
           </widget>
          </item>
         </layout>
        </item>
       </layout>
      </widget>
      <widget class="QMenuBar" name="menuBar">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>400</width>
         <height>25</height>
        </rect>
       </property>
      </widget>
      <widget class="QToolBar" name="mainToolBar">
       <attribute name="toolBarArea">
        <enum>TopToolBarArea</enum>
       </attribute>
       <attribute name="toolBarBreak">
        <bool>false</bool>
       </attribute>
      </widget>
      <widget class="QStatusBar" name="statusBar"/>
     </widget>
     <layoutdefault spacing="6" margin="11"/>
     <resources/>
     <connections/>
    </ui>