rika
rika10. Februar 2019 22:45

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.

Рекомендуємо хостинг TIMEWEB
Рекомендуємо хостинг TIMEWEB
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.

Magst du es? In sozialen Netzwerken teilen!

7
Evgenii Legotckoi
  • 11. Februar 2019 04:27

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
    • 25. Februar 2019 03:02
    • (bearbeitet)

    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
      • 25. Februar 2019 04:17

      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
        • 1. März 2019 03:00

        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
          • 1. März 2019 05:47

          Sorry, I don't know this moment.

            rika
            • 4. März 2019 05:38
            • (bearbeitet)

            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
              • 5. März 2019 03:33

              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();
              }
              

                Kommentare

                Nur autorisierte Benutzer können Kommentare posten.
                Bitte Anmelden oder Registrieren
                Letzte Kommentare
                A
                ALO1ZE19. Oktober 2024 08:19
                Fb3-Dateileser auf Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
                ИМ
                Игорь Максимов5. Oktober 2024 07:51
                Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
                d
                dblas55. Juli 2024 11:02
                QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
                k
                kmssr8. Februar 2024 18:43
                Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
                Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
                Jetzt im Forum diskutieren
                J
                JacobFib17. Oktober 2024 03:27
                добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
                JW
                Jhon Wick1. Oktober 2024 15:52
                Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
                КГ
                Кирилл Гусарев27. September 2024 09:09
                Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
                F
                Fynjy22. Juli 2024 04:15
                при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

                Folgen Sie uns in sozialen Netzwerken