rika
rikaFeb. 10, 2019, 10:45 p.m.

Help sending files via COM port

I have 2 separate computers connected by COM port, I want to write an application in QT to send 1 txt file from machine 1 to machine 2. Do you have any specific examples about it? I really need them. Thank you.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

7
Evgenii Legotckoi
  • Feb. 11, 2019, 4:27 a.m.

Hello,

I think, the same example in this article . This article was wrote by another user. But, in my opinion, it is nearest example with serial port for your question on this site.

    rika
    • Feb. 25, 2019, 3:02 a.m.
    • (edited)

    Thank you for your help. I did it. But I have some problems, this is my code:
    I only sent 1 txt file, but when I received it, I received 3 txt files, the first file was divided into 3 files.

    void MayInternet::serialReceived()
    {
    //Tao file nhan
    QDateTime local= QDateTime::currentDateTime();
    bool checkfile=true;
    if (checkfile)
    {
        QString filename="TinNhan"+local.date().toString("dd.MM.yyyy")+local.time().toString("hh.mm.ss")+".txt";
        if (Name!=filename)
        {
            Name=filename;
            checkfile=false;
        }
    }
    QFile file(Name);
    if (!file.open(QFile::Append | QFile::Text))
    {
        QMessageBox::warning(this, "Canh bao", "Khong tao duoc file / File khong ton tai. " + file.errorString());
        return ;
    }
    //Kiem tra du lieu tu cong va ghi vao file
    if(serialPort->bytesAvailable())
    {
        QByteArray datas = serialPort->readAll();
        if(datas.size()>0)
        {
            if(file.isOpen())
            {
                 QTextStream in(&file);
                 in<<datas;                 
            }
            file.close();
        }
        else {
            QMessageBox::warning(this, "Cảnh báo", "Không có dữ liệu. " + file.errorString());
            return;
        }
        if(serialPort->atEnd())
        {
            checkfile=true;
        }
    }
    
      Evgenii Legotckoi
      • Feb. 25, 2019, 4:17 a.m.

      Hello,

      I think. It is technology limitation. You can't send big file in one message. Just concatenate this several messages to one file.

        rika
        • March 1, 2019, 3 a.m.

        I have another question: I use 9-pin COM port, I want PC1 just send only, PC2 only receive. Therefore I connect Tx of COM1 (PC1) to Rx of COM2 (PC2). In my file.txt there is MD5 to check PC2, if the received PC2 file is match with the original file. if the file is not match, how to PC1 be aware and send it again (without the connect Tx of PC2 to Rx of PC1

          Evgenii Legotckoi
          • March 1, 2019, 5:47 a.m.

          Sorry, I don't know this moment.

            rika
            • March 4, 2019, 5:38 a.m.
            • (edited)

            I have another question:I want to read data from the COM port and write to the txt file, after I finish writing, I will open the file and display the screen. The problem I have is, I have not received all the data, they have been displayed on the screen, and the data is not fully received. This is my code:

            doc () is the function that displays the screen

                QByteArray datas = serialPort->readAll();
                if(datas.size()>0)
                {
                    if(file.isOpen())
                    {
                         QTextStream in(&file);
                         in<<datas;
                    }
                    file.close();
            
                }
                else {
                    QMessageBox::warning(this, "Cảnh báo", "Không có dữ liệu. " + file.errorString());
                    return;
                }
            if(serialPort->atEnd())
            {
                doc();
            }
            
              Evgenii Legotckoi
              • March 5, 2019, 3:33 a.m.

              Do you have all information in txt file if you open this file in standard windows notepad?

              Under Windows OS method readAll() works badly.

              Try this variant

              QFile inputFile(fileName);
              if (inputFile.open(QIODevice::ReadOnly))
              {
                 QTextStream in(&inputFile);
                 while (!in.atEnd())
                 {
                    QString line = in.readLine();
                    ...
                 }
                 inputFile.close();
              }
              

                Comments

                Only authorized users can post comments.
                Please, Log in or Sign up
                d
                • dsfs
                • April 26, 2024, 2:56 p.m.

                C ++ - Test 004. Pointers, Arrays and Loops

                • Result:80points,
                • Rating points4
                d
                • dsfs
                • April 26, 2024, 2:45 p.m.

                C++ - Test 002. Constants

                • Result:50points,
                • Rating points-4
                d
                • dsfs
                • April 26, 2024, 2:35 p.m.

                C++ - Test 001. The first program and data types

                • Result:73points,
                • Rating points1
                Last comments
                k
                kmssrFeb. 9, 2024, 5:43 a.m.
                Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
                Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
                EVA
                EVADec. 25, 2023, 9:30 p.m.
                Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
                J
                JonnyJoDec. 25, 2023, 7:38 p.m.
                Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
                G
                GvozdikDec. 19, 2023, 8:01 a.m.
                Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
                Now discuss on the forum
                G
                GarApril 22, 2024, 3:46 p.m.
                Clipboard Как скопировать окно целиком в clipb?
                DA
                Dr Gangil AcademicsApril 20, 2024, 5:45 p.m.
                Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
                a
                a_vlasovApril 14, 2024, 4:41 p.m.
                Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
                Павел Дорофеев
                Павел ДорофеевApril 14, 2024, 12:35 p.m.
                QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
                f
                fastrexApril 4, 2024, 2:47 p.m.
                Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

                Follow us in social networks