rika
rikaАқп. 10, 2019, 10: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
Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.

Ол саған ұнайды ма? Әлеуметтік желілерде бөлісіңіз!

7
Evgenii Legotckoi
  • Ақп. 11, 2019, 4: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, 2019, 3:02 Т.Ж.
    • (өңделген)

    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, 2019, 4: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, 2019, 3 Т.Ж.

        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, 2019, 5:47 Т.Ж.

          Sorry, I don't know this moment.

            rika
            • Наурыз 4, 2019, 5:38 Т.Ж.
            • (өңделген)

            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, 2019, 3: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();
              }
              

                Пікірлер

                Тек рұқсаты бар пайдаланушылар ғана пікір қалдыра алады.
                Кіріңіз немесе Тіркеліңіз
                Г

                C++ - Тест 001. Первая программа и типы данных

                • Нәтиже:66ұпай,
                • Бағалау ұпайлары-1
                t

                C++ - Тест 001. Первая программа и типы данных

                • Нәтиже:33ұпай,
                • Бағалау ұпайлары-10
                t

                Qt - Тест 001. Сигналы и слоты

                • Нәтиже:52ұпай,
                • Бағалау ұпайлары-4
                Соңғы пікірлер
                G
                GoattRockҚыр. 3, 2024, 1:50 Т.Қ.
                Linux жүйесінде файлдарды қалай көшіруге болады Задумывались когда-нибудь о том, как мы привыкли доверять свои вещи службам грузоперевозок? Сейчас такие услуги стали неотъемлемой частью нашей жизни, особенно когда речь идет о переездах между …
                d
                dblas5Шілде 5, 2024, 11:02 Т.Ж.
                QML - Сабақ 016. SQLite деректер қоры және онымен QML Qt-та жұмыс істеу Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
                k
                kmssrАқп. 8, 2024, 6:43 Т.Қ.
                Qt Linux - Сабақ 001. Linux астында Autorun Qt қолданбасы как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
                АК
                Анатолий КононенкоАқп. 5, 2024, 1:50 Т.Ж.
                Qt WinAPI - Сабақ 007. Qt ішінде ICMP Ping арқылы жұмыс істеу Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
                Енді форумда талқылаңыз
                Evgenii Legotckoi
                Evgenii LegotckoiМаусым 24, 2024, 3:11 Т.Қ.
                добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
                F
                FynjyШілде 22, 2024, 4:15 Т.Ж.
                при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …
                BlinCT
                BlinCTМаусым 25, 2024, 1 Т.Ж.
                Нарисовать кривую в qml Всем привет. Имеется Лист листов с тосками, точки получаны интерполяцией Лагранжа. Вопрос, как этими точками нарисовать кривую? ChartView отпадает сразу, в qt6.7 появился новый элемент…
                BlinCT
                BlinCTМамыр 5, 2024, 5:46 Т.Ж.
                Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
                Evgenii Legotckoi
                Evgenii LegotckoiМамыр 2, 2024, 2:07 Т.Қ.
                Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.

                Бізді әлеуметтік желілерде бақылаңыз