Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB
Feb. 11, 2019, 3:45 a.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.

Virtual hosting with 10 percent discount
Virtual hosting with 10 percent discount
EVILEG offers reliable hosting with a 10% discount for virtual hosting and 5% for VPS
7

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.

0
  • Feb. 25, 2019, 8: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;
    }
}
0

Hello,

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

1
  • March 1, 2019, 8 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

0

Sorry, I don't know this moment.

0
  • March 4, 2019, 10: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();
}
0

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
April 26, 2019, 2:45 a.m.
djanaibekova_0301@mail.ru

C++ - Тест 003. Условия и циклы

  • Result:42points,
  • Rating points-8
Z
April 25, 2019, 8:02 p.m.
ZadvornyAlexey

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

  • Result:60points,
  • Rating points-1
m
April 24, 2019, 2:30 p.m.
maksImkа

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
April 21, 2019, 4:22 p.m.
Евгений Легоцкой

Через метод setIcon table.horizontalHeaderItem(0).setIcon("qrc://path/to/icon.png")
April 21, 2019, 3:48 p.m.
Евгений Легоцкой

Добрый день! Спасибо за комментарий. Там действительно лучше будет сделать с инициализацией по умолчанию.
U
April 18, 2019, 3:37 p.m.
Unreal_man

А как иконку в хедер задать?
u
April 18, 2019, 2:15 a.m.
uaa

доброго времени,большое спасибо за пример для начинающего)при адаптации к своему проекту столкнулся с таким ньансом:в vepolyline.h в 47 строке нужна инициализация по умолчанию: int m_pointF...
E
April 11, 2019, 12:49 p.m.
Evgeny

Спасибо за ответ) У меня компоновщик на нее ругался просто. Оказалось, просто забыл Q_OBJECT в начале класса указать.
Now discuss on the forum
April 25, 2019, 10:51 a.m.
Ruslan Polupan

Изменил функциютеперь работает. bool ModelTerminals::setData(const QModelIndex &index, const QVariant &value, int role){ Q_UNUSED(role) if(!index.isValid()) {return false;...
April 24, 2019, 6:20 a.m.
Ruslan Polupan

я так понимаю надо инфорация об устройствах.Я бы пробовал так rust@suse:~> lsblk -PNAME="sda" MAJ:MIN="8:0" RM="0" SIZE="111,8G" RO="0" TYPE="disk" MOUNTPOINT=""NAME="sda1" MAJ:MIN="8...
April 21, 2019, 4:16 p.m.
Евгений Легоцкой

Приветствую Нужно сохранять где-то выбранное значение, а потом восстанавливать его. Или использовать QSettings или добавить метод open(), в который передавать начальные значения для того...
R
April 19, 2019, 9:55 a.m.
RED_Spider

мені важко це зараз навіть перевірити, тому що знайшов коміт, це ще було в 2016 році, і цей код не буде працювати коректно зараз, єдине скажу що це були QThread
Join us in social networks

For registered users on the site there is a minimum amount of advertising