Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Serial port Communication with pc through serial Adapter



  • I have tried to send the data over serial adapter . I have a text file , on that file i have four lines -

    i have attached the image , these are the lines in textfile ,

    alternate text

    I have tried to send these data to another pc by Qt .
    If i click the send button , the data is send to another pc by serial adapter , i have the output like this

    alternate text

    i got the output as per the image ..

    but what i want is IN RECEIVER is ,
    line 1
    it sends means i want to get back a acknowlgement and after getting acknolgemnt in my pc
    line 2 is send
    same thing is want to repeat

    i have tried by own thought , but i get a output as a single line .. as per the above image
    and my code is attached below , please give me some idea for this ..

    MAINWINDOW.CPP

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QList>
    #include <QComboBox>
    #include <QString>
    #include <QTextEdit>
    #include <QTime>
    #include <QDebug>
    #include <QtSerialPort/QSerialPortInfo>
    #include <QtSerialPort>
    #include <QFile>
    #include <QList>
    
      QString line ;
      QString txt3;
    QSerialPort *serial;
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        QList<QSerialPortInfo> list;
        list = QSerialPortInfo::availablePorts();
    
        for (int i= 0; i < list.length(); i++)
        {
            ui->comboBox->addItem(list[i].portName());
    
        }
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
        serial->close();
    }
    
    
    void MainWindow::on_pushButton_clicked()
    {
        serial = new QSerialPort (this) ;
        serial->setPortName(ui->comboBox->currentText());
        serial->setBaudRate (QSerialPort::Baud115200);
        serial->setDataBits(QSerialPort::Data8);
        serial->setParity (QSerialPort::NoParity);
        serial->setStopBits (QSerialPort::OneStop);
        serial->setFlowControl(QSerialPort::NoFlowControl);
        serial->open(QIODevice::ReadWrite);
        connect(serial,SIGNAL(readyRead()),this, SLOT (serialReceived()));
        ui->progressBar->setValue(100);
    
    
    }
    
    void MainWindow::on_send_clicked()
    {
         line   = ui->sender->toPlainText();
        QString txt1 = ui->receive->toPlainText();
        /*QString*/ txt3 = ui->aknowmnt->toPlainText();
        QFile inputFile(QString("/home/adx-soft1/Shankar/serial/myfile1.txt"));
        inputFile.open(QIODevice::ReadOnly);
        if (!inputFile.isOpen())
            return;
    
        QTextStream stream(&inputFile);
        line = stream.readLine();
        while (!line.isNull()) {
                QByteArray inBytes;
                const char*Data;
                inBytes = line.toUtf8();
                Data = inBytes.constData();
    
                QString StringData;
                StringData = QString:: fromUtf8(Data);
                serial->write(Data);
                line = stream.readLine();
        }
        ui->aknowmnt->setText("Sent Message -->" "\n"+ txt3 + line + "\n");
        ui->sender->clear();
    }
    
    void MainWindow::serialReceived()
    {
        QString glen = serial->readAll();
        if (glen.length()>0){
        /*QString*/ line = ui->receive->toPlainText();
    
        ui->receive->setText(line + "\n" + glen + "\n");
        line = txt3;
        }
    }
    
    

    Give Me some suggestions , what i want to change
    Thanks in Advance ...



  • From the top of my head, I'd serialise communication via QByteArray, so the workflow would be: QString > QByteArray -----> QByteArray > QString.

    Further on: I am not sure if I understand exactly what your workflow should be, so please correct me if I'm wrong.
    What I understand is, that you send line1 and wait for ack? I am not sure if your implementation is valid then, considering asynchronous nature of QSerialPort.

    Also, is there a reason you convert QString to plain text?



  • @sankarapandiyan said in Serial port Communication with pc through serial Adapter:

    serial->write(Data);

    If you use QSerialPort::write(const char *data), write will stop on first 0 byte according to documentation => https://doc.qt.io/qt-5/qiodevice.html#write-1

    You don't need to convert to plaint text, for binary data it is easier to use QByteArray

    QTextStream stream(&inputFile);
        line = stream.readLine();
        while (!line.isNull()) {
                QByteArray outBytes = line.toUtf8();
                serial->write(outBytes);
                line = stream.readLine();
        }
    


  • @artwaw said in Serial port Communication with pc through serial Adapter:

    What I understand is, that you send line1 and wait for ack?

    Yes you are cent percent right ... Is there is any possibility to get a ack from the PC by the code...



  • @KroMignon said in Serial port Communication with pc through serial Adapter:

    QTextStream stream(&inputFile);
    line = stream.readLine();
    while (!line.isNull()) {
    QByteArray outBytes = line.toUtf8();
    serial->write(outBytes);
    line = stream.readLine();
    }

    Yes Even i have tried liked this , Even the output is like

    alternate text

    Still the output is in single line i want it as line by line but i cant , give me some idea to do this task ..


  • Lifetime Qt Champion

    @sankarapandiyan said in Serial port Communication with pc through serial Adapter:

    i want it as line by line

    Then put it line by line into your text edit. What is the problem with this?
    You can simply put a new line after each line:

    ui->textEdit->setText(ui->textEdit->text() + '\n' + line);
    


  • @jsulm

    QTextStream stream(&inputFile);
       line = stream.readLine();
       while (!line.isNull()) {
               QByteArray inBytes;
               inBytes = line.toUtf8();
               serial->write(inBytes+ "\r" "\n"); // here i have added the "\r" and "\n" for split the word one by one 
               line = stream.readLine();
       }
    

    I have a output like this ...
    alternate text

    now its fine ...
    But , if i press the send button its sends all the lines at the time. i need aknlment before sending the next word , so its want to repeat

    Example , if i press the send button

    line1 is in the recevier (another pc) ------- sended line1 in the aknowldgement (in my pc )
    after getting aknwldgmnt ,
    the line 2 wants to send (another pc) ---------- sended line2 in the aknowldgmnt (in my pc )

    like wis it repeats for the four lines in the text file ..

    Here how to get a aknowldgement in my code this is my code .. Give me some suggestions ..

    void MainWindow::on_send_clicked()
    {
         line   = ui->sender->toPlainText();
        QString txt1 = ui->receive->toPlainText();
        /*QString*/ txt3 = ui->aknowmnt->toPlainText();
        QFile inputFile(QString("/home/adx-soft1/Shankar/serial/myfile1.txt"));
        inputFile.open(QIODevice::ReadOnly);
        if (!inputFile.isOpen())
            return;
    
        QTextStream stream(&inputFile);
        line = stream.readLine();
        while (!line.isNull()) {
                QByteArray inBytes;
                inBytes = line.toUtf8();
                serial->write(inBytes+ "\r" "\n");
                line = stream.readLine();
        }
        ui->aknowmnt->setText("Sent Message -->" "\n"+  line + "\n");
    }
    
    void MainWindow::serialReceived()
    {
        QString glen = serial->readAll();
        if (glen.length()>0){
        /*QString*/ line = ui->receive->toPlainText();
        ui->receive->setText(ui->receive->toPlainText()+line+"\n");
        ui->receive->setText(line + "\r\n" + glen + "\r\n");
        line = txt3;
        }
    }
    
    

  • Lifetime Qt Champion

    @sankarapandiyan Well, currently you send everything at once in one loop. Do you have a protocol? I mean, the other side has to send an ack. Then it would work like this: you connect a signal to readyRead(), send first line, in slot connected to readyRead you read the ack and send next line and so on until you sent everything.


  • Moderators

    @sankarapandiyan
    here,
    a very crude implementation on how one could do it

    void MainWindow::checkAndSendData()
    {
        if(!m_lines.isEmpty()){
            QByteArray baToSend = m_lines.takeFirst().toUtf8();
            serial->write(baToSend);
            ui->aknowmnt->setText("Sent Message -->" "\n"+  QString(baToSend) + "\n");
        } else {
            ui->aknowmnt->setText("All send");
        }
    }
    
    void MainWindow ::on_send_clicked()
    {
        line   = ui->sender->toPlainText();
            QString txt1 = ui->receive->toPlainText();
            /*QString*/ txt3 = ui->aknowmnt->toPlainText();
            
            //m_lines is a member QStringList
            if(m_lines.isEmpty()){
                QFile inputFile(QString("/home/adx-soft1/Shankar/serial/myfile1.txt"));
                inputFile.open(QIODevice::ReadOnly);
                if (!inputFile.isOpen())
                    return;
            
                QTextStream stream(&inputFile);
                while(!stream.atEnd()){
                    QString line = stream.readLine();
                    m_lines.append(line + QString("\r\n"));
                }
            }
            
            checkAndSendData();
    }
    
    void MainWindow::serialReceived()
    {
        QString glen = serial->readAll();
        if (glen.length()>0){
        /*QString*/ line = ui->receive->toPlainText();
        ui->receive->setText(ui->receive->toPlainText()+line+"\n");
        ui->receive->setText(line + "\r\n" + glen + "\r\n");
        line = txt3;
        }
        
        checkAndSendData();
    }
    


  • @J-Hilk

    Hi i have used the code , finally i got the acknowldgement

    alternate text

    But i want to send it automatically , Here i am pressing send button for every data , like if i click the send button first time , it sends the line 1 only , i want to send the line 1 and line 2 and line 3 and line 4 with single click but at the time the the ack also i want to get automatically .

    Is it possible to get like this ..

    this is my Edited Code ..

    void MainWindow::checkAndSendData()
    {
        if(!m_lines.isEmpty()){
            QByteArray inBytes;
            QByteArray baToSend = m_lines.takeFirst().toUtf8();
            serial->write(baToSend);
            ui->aknowmnt->setText("Sent Message -->" "\n"+ QString(baToSend) + "\n");
        } else {
            ui->aknowmnt->setText("All send");
        }
    }
    
    void MainWindow::on_send_clicked()
    {
         line   = ui->sender->toPlainText();
        QString txt1 = ui->receive->toPlainText();
        /*QString*/ txt3 = ui->aknowmnt->toPlainText();
    
         if(m_lines.isEmpty()){
        QFile inputFile(QString("/home/adx-soft1/Shankar/serial/myfile1.txt"));
        inputFile.open(QIODevice::ReadOnly);
        if (!inputFile.isOpen())
            return;
    
        QTextStream stream(&inputFile);
        while (!stream.atEnd()){
                line = stream.readLine();
                m_lines.append(line+QString("\r\n"));
        }
         }
         checkAndSendData();
    }
    
    void MainWindow::serialReceived()
    {
        QString glen = serial->readAll();
        if (glen.length()>0){
        /*QString*/ line = ui->receive->toPlainText();
        ui->receive->setText(ui->receive->toPlainText()+line+"\n");
        ui->receive->setText(line + "\r\n" + glen + "\r\n");
        line = txt3;
        }
       checkAndSendData();
    }
    
    

    Give_Me_Some_Solution_for_this_Sir.


  • Moderators

    @sankarapandiyan
    šŸ¤”

    It should do that automatically.
    See the checkAndSendData();at the end of your serialReceived function. That will call the same function to write the next line.

    same as button pressed again.

    are you sure serialReceived is actually called?



  • @J-Hilk yes i called the function , But i didnot get it automatically

    void MainWindow::serialReceived()
    {
        QString glen = serial->readAll();
        if (glen.length()>0){
        /*QString*/ line = ui->receive->toPlainText();
        ui->receive->setText(ui->receive->toPlainText()+line+"\n");
        ui->receive->setText(line + "\r\n" + glen + "\r\n");
        line = txt3;
        }
       checkAndSendData();
    }
    
    

  • Lifetime Qt Champion

    @sankarapandiyan Is your serialReceived() called?



  • @jsulm said in Serial port Communication with pc through serial Adapter:

    Is your serialReceived() called?

    serial received called in where ? i didnt understand , actually i acalled checkAndSendData(); in Serial received ..

    But i dont know where to call serialReceived() Function in my code


  • Lifetime Qt Champion

    @sankarapandiyan serialReceived() is a slot and needs to be connected to readRead signal - did you connect it? Else it will not be called when you get ack.



  • @jsulm @J-Hilk I Have tried like this

    void MainWindow::on_send_clicked()
    {
         line   = ui->sender->toPlainText();
        QString txt1 = ui->receive->toPlainText();
        /*QString*/ txt3 = ui->aknowmnt->toPlainText();
    
         if(m_lines.isEmpty()){
        QFile inputFile(QString("/home/adx-soft1/Shankar/serial/myfile1.txt"));
        inputFile.open(QIODevice::ReadOnly);
        if (!inputFile.isOpen())
            return;
    
        QTextStream stream(&inputFile);
        while (!stream.atEnd()){
                line = stream.readLine();
                m_lines.append(line+QString("\r\n"));
        }
    
         }
         checkAndSendData();
         serialReceived(); // Here I have call a function but it also make no sense i think.
    }
    

  • Lifetime Qt Champion

    @sankarapandiyan This does not answer my question.
    Did you connect serialReceived() to readyRead()? Can you please answer this question?


  • Moderators

    @sankarapandiyan
    you're right, it makes no sense there.

    serialReceived should be a slot (and it has to be markt as such inside your header file) that is called when the serial port emits the readyRead signal.

    Ideale, you should never call this slot manually, from within your own source code.

    change your connect to the new syntax
    from

    connect(serial,SIGNAL(readyRead()),this, SLOT (serialReceived()));

    to

    connect(serial, &QSerialPort::readyRead,this, &MainWindow::serialReceived);

    It should/could solve a couple of issues



  • @jsulm said in Serial port Communication with pc through serial Adapter:

    This does not answer my question.
    Did you connect serialReceived() to readyRead()? Can you please answer this question?
    Yes Connected..

    void MainWindow::on_pushButton_clicked()
    {
        serial = new QSerialPort (this) ;
        serial->setPortName(ui->comboBox->currentText());
        serial->setBaudRate (QSerialPort::Baud115200);
        serial->setDataBits(QSerialPort::Data8);
        serial->setParity (QSerialPort::NoParity);
        serial->setStopBits (QSerialPort::OneStop);
        serial->setFlowControl(QSerialPort::NoFlowControl);
        serial->open(QIODevice::ReadWrite);
        connect(serial,SIGNAL(readyRead()),this, SLOT (serialReceived())); //**HERE_I_CONNECTED_THE_SERIALRECEIVED_SLOT**
        ui->progressBar->setValue(100);
    //    ui->receive->clear();
    }
    

  • Lifetime Qt Champion

    @sankarapandiyan OK, I didn't noticed, sorry.
    Check @J-Hilk response and make sure your slot is called (put a qDebug() there).



  • @J-Hilk said in Serial port Communication with pc through serial Adapter:

    connect(serial, &QSerialPort::readyRead,this, &MainWindow::serialReceived);

    Thanks a lot . I have changed the code
    from

    connect(serial,SIGNAL(readyRead()),this, SLOT (serialReceived()));

    to

    connect(serial, &QSerialPort::readyRead,this, &MainWindow::serialReceived);
    but same output is came



  • @sankarapandiyan said in Serial port Communication with pc through serial Adapter:

    connect(serial,SIGNAL(readyRead()),this, SLOT (serialReceived())); //HERE_I_CONNECTED_THE_SERIALRECEIVED_SLOT

    You should prefer using new connect style, so connect validity will be checked at compilation:

    connect(serial, &QSerialPort::readyRead,this, &MainWindow::serialReceived);
    

    And then in the slot:

    void MainWindow::serialReceived()
    {
        QByteArray rawData;
        while(!serial->atEnd())
        {
            rawData.append(serial->readAll());
        }
        if(!rawData.isEmpty())
        {
            QString glen = QString(rawDaa);
           /*QString*/ line = ui->receive->toPlainText();
           ui->receive->setText(ui->receive->toPlainText()+line+"\n");
           ui->receive->setText(line + "\r\n" + glen + "\r\n");
           line = txt3;
        }
        checkAndSendData();
    }
    

    Or if you are sure always receiving a '\r' or '\n' from your device, you can do it like this:

    void MainWindow::serialReceived()
    {
        while(serial->canReadLine())
        {
            QString glen = QString(serial->readLine());
           /*QString*/ line = ui->receive->toPlainText();
           ui->receive->setText(ui->receive->toPlainText()+line+"\n");
           ui->receive->setText(line + "\r\n" + glen + "\r\n");
           line = txt3;
        }
        checkAndSendData();
    }
    

    look at documentation ==> https://doc.qt.io/qt-5/qserialport.html#canReadLine


  • Moderators

    As I don't have a serial dive at hand that returns data I can't debug it for you.

    Start the debugger (F5) set a breakpoint in serialReceived and step over/in via F10/F11 and see what happens

    That said, I vaguely remember that one should not call write from the slot that is connected to readyRead ( my be wrong here )

    So you could try:

    void MainWindow::serialReceived()
    {
        ....
        QMetaObject::invokeMethod(this, &MainWindow::checkAndSendData, Qt::QueuedConnection);
    }
    

    to push the write to the next event loop cycle



  • @KroMignon said in Serial port Communication with pc through serial Adapter:

    You should prefer using new connect style, so connect validity will be checked at compilation:
    connect(serial, &QSerialPort::readyRead,this, &MainWindow::serialReceived);

    I want to change this
    from -
    -->connect(serial,SIGNAL(readyRead()),this, SLOT (serialReceived()))
    to
    -->connect(serial, &QSerialPort::readyRead,this, &MainWindow::serialReceived);

    Like this you are saying ?

    I tried by your words , and i have edited my code , this is my code i have attached below

    void MainWindow::on_pushButton_clicked()
    {
        serial = new QSerialPort (this) ;
        serial->setPortName(ui->comboBox->currentText());
        serial->setBaudRate (QSerialPort::Baud115200);
        serial->setDataBits(QSerialPort::Data8);
        serial->setParity (QSerialPort::NoParity);
        serial->setStopBits (QSerialPort::OneStop);
        serial->setFlowControl(QSerialPort::NoFlowControl);
        serial->open(QIODevice::ReadWrite);
       // connect(serial,SIGNAL(readyRead()),this, SLOT (serialReceived()));
        connect(serial, &QSerialPort::readyRead,this, &MainWindow::serialReceived);
    
       ui->progressBar->setValue(100);
    //    ui->receive->clear();
    }
    
    void MainWindow::checkAndSendData()
    {
        if(!m_lines.isEmpty()){
            QByteArray inBytes;
            QByteArray baToSend = m_lines.takeFirst().toUtf8();
            serial->write(baToSend);
            ui->aknowmnt->setText("Sent Message -->" "\n"+ QString(baToSend) + "\n");
        } else {
            ui->aknowmnt->setText("Receiving ");
        }
    }
    
    void MainWindow::on_send_clicked()
    {
         line   = ui->sender->toPlainText();
        QString txt1 = ui->receive->toPlainText();
        /*QString*/ txt3 = ui->aknowmnt->toPlainText();
    
         if(m_lines.isEmpty()){
        QFile inputFile(QString("/home/adx-soft1/Shankar/serial/myfile1.txt"));
        inputFile.open(QIODevice::ReadOnly);
        if (!inputFile.isOpen())
            return;
    
        QTextStream stream(&inputFile);
        while (!stream.atEnd()){
                line = stream.readLine();
                m_lines.append(line+QString("\r\n"));
        }
    
         }
         checkAndSendData();
    
    }
    void MainWindow::serialReceived()
    {
        QByteArray rawData;
        while(!serial->atEnd())
        {
            rawData.append(serial->readAll());
        }
        if(!rawData.isEmpty())
        {
            QString glen = QString(rawData);
           /*QString*/ line = ui->receive->toPlainText();
           ui->receive->setText(ui->receive->toPlainText()+line+"\n");
           ui->receive->setText(line + "\r\n" + glen + "\r\n");
           line = txt3;
        }
        checkAndSendData();
    }
    

    and my output is sended like this ,

    alternate text

    I Dont know what is the Exact problem is



  • @sankarapandiyan
    You need to set a timer to delay some time after each serial write.



  • @small_bird ok fine , But is it possible to send the all data with in just a one click with ack ..! that is my exact problem



  • @J-Hilk You are saying like this ?

    void MainWindow::serialReceived()
    
    {
        QMetaObject::invokeMethod(this, &MainWindow::checkAndSendData, Qt::QueuedConnection);
        
        QString glen = serial->readAll();
        if (glen.length()>0){
        /*QString*/ line = ui->receive->toPlainText();
        ui->receive->setText(ui->receive->toPlainText()+line+"\n");
        ui->receive->setText(line + "\r\n" + glen + "\r\n");
        line = txt3;
        }
       checkAndSendData();
    }
    
    

  • Moderators

    @sankarapandiyan

    void MainWindow::serialReceived()
    {
        ....
        QMetaObject::invokeMethod(this, &MainWindow::checkAndSendData, Qt::QueuedConnection);
    }
    
    void MainWindow::serialReceived()
    
    {
        QString glen = serial->readAll();
        if (glen.length()>0){
        /*QString*/ line = ui->receive->toPlainText();
        ui->receive->setText(ui->receive->toPlainText()+line+"\n");
        ui->receive->setText(line + "\r\n" + glen + "\r\n");
        line = txt3;
        }
       QMetaObject::invokeMethod(this, &MainWindow::checkAndSendData, Qt::QueuedConnection);
    }
    


  • @sankarapandiyan
    of course you can, define a queue and then put every line into the queue. every time ,get one from the queue and then put it into the serial port.



  • @J-Hilk said in Serial port Communication with pc through serial Adapter:

    void MainWindow::serialReceived()

    {
    QString glen = serial->readAll();
    if (glen.length()>0){
    /QString/ line = ui->receive->toPlainText();
    ui->receive->setText(ui->receive->toPlainText()+line+"\n");
    ui->receive->setText(line + "\r\n" + glen + "\r\n");
    line = txt3;
    }
    QMetaObject::invokeMethod(this, &MainWindow::checkAndSendData, Qt::QueuedConnection);
    }

    I Have tried this my output is same like this

    alternate text
    this is my code is there is any problem in my code

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QList>
    #include <QComboBox>
    #include <QString>
    #include <QTextEdit>
    #include <QTime>
    #include <QDebug>
    #include <QtSerialPort/QSerialPortInfo>
    #include <QtSerialPort>
    #include <QFile>
    #include <QList>
    
      QString line ;
      QString txt3;
    QSerialPort *serial;
    QStringList m_lines;
    //QByteArray rawData;
    
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
    {
    
        ui->setupUi(this);
    
        QString filename1="/home/adx-soft1/Shankar/serial/myfile1.txt";
          QFile file(filename1);
          if(!file.exists()){
              qDebug() << "NO FILE "<<filename1;
          }else{
              qDebug() << filename1<<" ...";
          }
          QString line1;
          ui->sender->clear();
          if (file.open(QIODevice::ReadOnly | QIODevice::Text)){ ui->sender->setText(file.readAll()); }
    
        QList<QSerialPortInfo> list;
        list = QSerialPortInfo::availablePorts();
    
        for (int i= 0; i < list.length(); i++)
        {
            ui->comboBox->addItem(list[i].portName());
    
        }
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
        serial->close();
    }
    
    
    void MainWindow::on_pushButton_clicked()
    {
        serial = new QSerialPort (this) ;
        serial->setPortName(ui->comboBox->currentText());
        serial->setBaudRate (QSerialPort::Baud115200);
        serial->setDataBits(QSerialPort::Data8);
        serial->setParity (QSerialPort::NoParity);
        serial->setStopBits (QSerialPort::OneStop);
        serial->setFlowControl(QSerialPort::NoFlowControl);
        serial->open(QIODevice::ReadWrite);
        connect(serial,SIGNAL(readyRead()),this, SLOT (serialReceived()));
    //    connect(serial, &QSerialPort::readyRead,this, &MainWindow::serialReceived);
    
       ui->progressBar->setValue(100);
    //    ui->receive->clear();
    }
    
    void MainWindow::checkAndSendData()
    {
        if(!m_lines.isEmpty()){
            QByteArray inBytes;
            QByteArray baToSend = m_lines.takeFirst().toUtf8();
            serial->write(baToSend);
            ui->aknowmnt->setText("Sent Message -->" "\n"+ QString(baToSend) + "\n");
        } else {
            ui->aknowmnt->setText("Receiving ");
        }
    }
    
    void MainWindow::on_send_clicked()
    {
         line   = ui->sender->toPlainText();
        QString txt1 = ui->receive->toPlainText();
        /*QString*/ txt3 = ui->aknowmnt->toPlainText();
    
         if(m_lines.isEmpty()){
        QFile inputFile(QString("/home/adx-soft1/Shankar/serial/myfile1.txt"));
        inputFile.open(QIODevice::ReadOnly);
        if (!inputFile.isOpen())
            return;
    
        QTextStream stream(&inputFile);
        while (!stream.atEnd()){
                line = stream.readLine();
                m_lines.append(line+QString("\r\n"));
        }
    
         }
         checkAndSendData();
    
    }
    void MainWindow::serialReceived()
    
    {
    
        QString glen = serial->readAll();
        if (glen.length()>0){
        /*QString*/ line = ui->receive->toPlainText();
        ui->receive->setText(ui->receive->toPlainText()+line+"\n");
        ui->receive->setText(line + "\r\n" + glen + "\r\n");
        line = txt3;
        }
       checkAndSendData();
       QMetaObject::invokeMethod(this, &MainWindow::checkAndSendData, Qt::QueuedConnection);
    
    }
    

    But I have not get the correct output @J-Hilk



  • @sankarapandiyan check your encode function



  • @small_bird Encode function means What you mean ? i didnt get you


  • Moderators

    @sankarapandiyan
    ok, lets simplify your code, I assume receive and aknowmntare QTextEdits or QTextBrowser, since they have a toPlainTextfunction

    void MainWindow::checkAndSendData()
    {
        if(!m_lines.isEmpty()){
            QByteArray baToSend = m_lines.takeFirst().toUtf8();
            serial->write(baToSend);
            ui->aknowmnt->append("Sent Message --> "+ QString(baToSend));
        } else {
            ui->aknowmnt->append("All are send ");
        }
    }
    
    void MainWindow::serialReceived()
    
    {
        QString glen = serial->readAll();
        if (glen.length()>0){
             ui->receive->append( "Received -->" + QString(glen));
        }
       QMetaObject::invokeMethod(this, &MainWindow::checkAndSendData, Qt::QueuedConnection);
    
    }
    


  • @J-Hilk

    Yes i have tried this method , the correct data is not shown in the receiver side ..

    alternate text

    void MainWindow::on_pushButton_clicked()
    {
        serial = new QSerialPort (this) ;
        serial->setPortName(ui->comboBox->currentText());
        serial->setBaudRate (QSerialPort::Baud115200);
        serial->setDataBits(QSerialPort::Data8);
        serial->setParity (QSerialPort::NoParity);
        serial->setStopBits (QSerialPort::OneStop);
        serial->setFlowControl(QSerialPort::NoFlowControl);
        serial->open(QIODevice::ReadWrite);
    //    connect(serial,SIGNAL(readyRead()),this, SLOT (serialReceived()));
        connect(serial, &QSerialPort::readyRead,this, &MainWindow::serialReceived);
    
       ui->progressBar->setValue(100);
    //    ui->receive->clear();
    }
    
    void MainWindow::checkAndSendData()
    {
        if(!m_lines.isEmpty()){
            QByteArray baToSend = m_lines.takeFirst().toUtf8();
            serial->write(baToSend);
            ui->aknowmnt->append("Sent Message --> "+ QString(baToSend));
        } else {
            ui->aknowmnt->append("All are send ");
        }
    }
    
    void MainWindow::on_send_clicked()
    {
         line   = ui->sender->toPlainText();
        QString txt1 = ui->receive->toPlainText();
        /*QString*/ txt3 = ui->aknowmnt->toPlainText();
    
         if(m_lines.isEmpty()){
        QFile inputFile(QString("/home/adx-soft1/Shankar/serial/myfile1.txt"));
        inputFile.open(QIODevice::ReadOnly);
        if (!inputFile.isOpen())
            return;
    
        QTextStream stream(&inputFile);
        while (!stream.atEnd()){
                line = stream.readLine();
                m_lines.append(line+QString("\r\n"));
        }
    
         }
         checkAndSendData();
    
    }
    
    void MainWindow::serialReceived()
    
    {
        QString glen = serial->readAll();
        if (glen.length()>0){
             ui->receive->append( "Received -->" + QString(glen));
        }
       QMetaObject::invokeMethod(this, &MainWindow::checkAndSendData, Qt::QueuedConnection);
    }
    


  • @J-Hilk said in Serial port Communication with pc through serial Adapter:

    ok, lets simplify your code, I assume receive and aknowmntare QTextEdits or QTextBrowser, since they have a toPlainTextfunction

    Yes Its a QTextEdits


  • Moderators

    @sankarapandiyan
    you're obviously receiving non ascii bytes

    void MainWindow::serialReceived()
    
    {
        QByteArray glen = serial->readAll();
        if (glen.length()>0){
             ui->receive->append( QString("Received --> %1").arg(QString(glen.toHex(' ')));
        }
       QMetaObject::invokeMethod(this, &MainWindow::checkAndSendData, Qt::QueuedConnection);
    
    }
    


  • @J-Hilk said in Serial port Communication with pc through serial Adapter:

    void MainWindow::serialReceived()

    {
    QByteArray glen = serial->readAll();
    if (glen.length()>0){
    ui->receive->append( QString("Received --> %1").arg(QString(glen.toHex(' ')));
    }
    QMetaObject::invokeMethod(this, &MainWindow::checkAndSendData, Qt::QueuedConnection);

    }

    this out put is what i receive from another pc
    alternate text
    And the next below image is shown as a data send as some thing different

    alternate text

    Even Now also i did not get the exact output sir what should i do i am stuck here .. @J-Hilk



  • @sankarapandiyan Maybe it is a silly question, but are you sure the serial settings your are using, are correct?

    • 115200 bauds?
    • 8 bits?

    Are you using a crossed/null modem serial cable? ==> cf https://en.wikipedia.org/wiki/Null_modem.



  • @KroMignon I am Using hl-340 usb-serial adapter . so here , what i want to give as a baud rate.

    void MainWindow::on_pushButton_clicked()
    {
        serial = new QSerialPort (this) ;
        serial->setPortName(ui->comboBox->currentText());
        serial->setBaudRate (QSerialPort::Baud115200);
        serial->setDataBits(QSerialPort::Data8);
        serial->setParity (QSerialPort::NoParity);
        serial->setStopBits (QSerialPort::OneStop);
        serial->setFlowControl(QSerialPort::NoFlowControl);
        serial->open(QIODevice::ReadWrite);
        connect(serial,SIGNAL(readyRead()),this, SLOT (serialReceived()));
        ui->progressBar->setValue(100);
    //    ui->receive->clear();
    }
    


  • @sankarapandiyan said in Serial port Communication with pc through serial Adapter:

    I am Using hl-340 usb-serial adapter

    Okay, that's for having a RS232 port on you PC, but to connect two PC you need a "null modem" cable (to cross Tx and Rx signal between the 2 serial ports).
    Have you something like this?


Log in to reply