How to display data on console incoming data from the serial port
-
hi,
my aim write data and read data in serial port on console but I can not display to data on console. How to display data?
my code:
@#include <QTextStream>
#include <QCoreApplication>
#include <QStringList>
#include <QtSerialPort/QSerialPort>
#include <iostream>
#include <QDebug>
#include <QByteArray>int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);QSerialPort serialPort; QTextStream standardOutput(stdout); QString serialPortName = "COM1"; serialPort.setPortName(serialPortName); int serialPortBaudRate = QSerialPort::Baud9600; if(serialPort.setBaudRate(serialPortBaudRate)) { std::cout<<"asd\n\n"<<serialPortBaudRate<<"\n\n"; } if (!serialPort.open(QIODevice::ReadWrite)) { std::cout<<"Failed to open port"; return 1; } char data; std::cin>>data; serialPort.write(&data); QByteArray readData = serialPort.readAll(); readData.append(serialPort.readAll()); qDebug()<<readData; standardOutput << readData<< endl; return a.exec();
}@
thanks
-
You are doing everything in the main. So you may not be reading the data at all from SerialPort. You better work with Signal and Slots. There is readyRead() signal for serial port. You better put this signal and connect to slot. When ever the data comes it calls the slot. Inside the slot you can read the data and print the same. Also you can try with waitForReadyRead() method as well.
-
Hi,
The a.exec() command will start the application event loop, so anything before that (without the call to handle the eventhandler) will not work with signal/slot or events. In your case you dump some data on the seriel port with the write command and then immediate read some data from that port (which is probably empty, cause only usec before you created the port class). Thus your readData will always remain empty.
Better to setup a MainWindow (or any other type of class) that starts a seriel port and setup a slot for the readyread signal. Then when data is received your slot will be called and there is data in the read buffer. -
I don't know use signal and slot but I will learn in a shortest time and I will apply.
thanks
-
Hi,
To add to what has already been said, you have to first open QSerialPort and then setup the device