Qt serial port program crashes when run on another system - c++

I modified this code on a Windows 10 PC, and it compiled and ran without crashing.
#include <QtSerialPort/QSerialPort>
#include <QTextStream>
#include <QCoreApplication>
#include <QFile>
#include <QStringList>
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
QCoreApplication coreApplication(argc, argv);
int argumentCount = QCoreApplication::arguments().size();
QStringList argumentList = QCoreApplication::arguments();
QTextStream standardOutput(stdout);
if (argumentCount == 1) {
standardOutput << QObject::tr("Usage: %1 <serialportname> [baudrate]").arg(argumentList.first()) << endl;
return 1;
}
QSerialPort serialPort;
QString serialPortName = argumentList.at(1);
serialPort.setPortName(serialPortName);
int serialPortBaudRate = (argumentCount > 2) ? argumentList.at(2).toInt() : QSerialPort::Baud9600;
serialPort.setBaudRate(serialPortBaudRate);
if (!serialPort.open(QIODevice::WriteOnly)) {
standardOutput << QObject::tr("Failed to open port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
}
QFile dataFile("C:\\SerialCommand.dat");
if (!dataFile.open(QIODevice::ReadOnly)) {
standardOutput << QObject::tr("Failed to open file for reading") << endl;
return 1;
}
QByteArray writeData(dataFile.readAll());
dataFile.close();
if (writeData.isEmpty()) {
standardOutput << QObject::tr("Either no data was currently available on the standard input for reading, or an error occurred for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
}
qint64 bytesWritten = serialPort.write(writeData);
if (bytesWritten == -1) {
standardOutput << QObject::tr("Failed to write the data to port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
} else if (bytesWritten != writeData.size()) {
standardOutput << QObject::tr("Failed to write all the data to port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
} else if (!serialPort.waitForBytesWritten(5000)) {
standardOutput << QObject::tr("Operation timed out or an error occurred for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
}
standardOutput << QObject::tr("Data successfully sent to port %1").arg(serialPortName) << endl;
printf("\n\ntest");
return 0;
}
I set Qt to release mode, and packaged the application with the following .dll files:
msvcp120d.dll
msvcr120d.dll
Qt5Core.dll
Qt5Cored.dll
Qt5SerialPort.dll
Qt5SerialPortd.dll
Qt5Widgets.dll
qwindows.dll
When I ran the application on another system (also windows 10), the program crashes immediately - and yes, I did move SerialCommand.dat to its correct location on the C drive. Any thoughts?

You're packaging the debug versions of the dlls (ending with a d) instead of release ones.
Read the Qt deployment docs, especially the last part (from "Application Dependencies" to the end).
The dependency walker helps find the actual dependencies, and in theory windeployqt should automate the work of creating a release dir with all the files you need.
See also this other question, but it's for an app using QML, so it's more complex than your case.

Related

Debug console not blocked for std input required by library function

Every code works fine. Debugging with visual studio is problem.
I'm making Linux server using openSSL library with c++11.
The server runs on CentOS in VMware. (Will move to Azure when completed)
I work on Visual studio 2017, cross-compile linked with that CentOS.
When I call
int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type);
this funcntion in ssl library, it opens private key file, require me password on standard input, showing up message on standard out and wait for my input.
But if I run on Visual studio debug mode, it just passes away.
It works fine when I use .out file on CentOS, and that '.out' file is compiled by visual studio for debugging.
It's not a path problem. '.crt' file opens well and only '.key' file in the same folder not opens well.
these are the code where problem occur.
SslUtil, ExceptionSslUtil class is in my own code. but the other all functions and structures in this code are in ssl library.
void SslUtil::InitAsServer(const char* pathCert, const char* pathKey) {
amIServer = true;
SSL_load_error_strings();
SSLeay_add_ssl_algorithms();
meth = SSLv23_server_method();
ctx = SSL_CTX_new(meth);
if (!ctx)
throw ExceptionSslUtil("ctx create error");
if (SSL_CTX_use_certificate_file(ctx, pathCert, SSL_FILETYPE_PEM) <= 0)
throw ExceptionSslUtil("cert file open error");
if (SSL_CTX_use_PrivateKey_file( ctx, pathKey, SSL_FILETYPE_PEM) <= 0)// here's the problem.
throw ExceptionSslUtil("private key file open error");
if (!SSL_CTX_check_private_key(ctx))
throw ExceptionSslUtil("Private key does not match the certificate public keyn");
return;
}
SSL_CTX_use_PrivateKey_file function not blocked for input, just returning minus value. It has to wait for input but not.
I have no idea what's happening there.
It worked previously,
but when I change original main(argc, argv) function into mainSslEpoll(argc, argv) and make it called by other main function, this problem happen... why?
The following is my new main function.
int main(int argc, char** argv) {
string str;
while (true) {
cout << "select mode" << endl;
cout << "\t" << "0:SSL + Epoll server" << endl;
cout << "\t" << "1:SSL server" << endl;
cout << "\t" << "2:SSL client" << endl;
cin >> str;
if (str[0] == '0') return mainSslEpoll(argc, argv);
if (str[0] == '1') return mainSslServer(argc, argv);
if (str[0] == '2') return mainSslClient(argc, argv);
}
}

Program not working right on other windows machines

I'm having a problem with my application, in which I'm trying to get all network configurations of the system that it runs on. The final goal is to find the MAC address with highest priority.
The code runs ok and works when I run it with QtCreator and also runs ok when I create a folder containing the dll files and the exe file.
But the problem is that when I run this program on other windows machines (7 and 10) it runs but does not return or show anything. I tried running it as an Administrator, that didn't work neither and this code should be able to work on all windows platforms.
Any suggestions?
I'm currently on Windows 10 and using Qt 5.8 MSVC 2015
The exe file runs with these dlls on Windows 10:
Qt5Core.dll
Qt5Network.dll
msvcp140.dll
msvcr120.dll
vcruntime140.dll
These dlls should be also there for windows 7:
api-ms-win-core-file-l1-2-0.dll
api-ms-win-core-file-l2-1-0.dll
api-ms-win-core-localization-l1-2-0.dll
api-ms-win-core-processthreads-l1-1-1.dll
api-ms-win-core-string-l1-1-0.dll
api-ms-win-core-synch-l1-2-0.dll
api-ms-win-core-timezone-l1-1-0.dll
api-ms-win-crt-convert-l1-1-0.dll
api-ms-win-crt-environment-l1-1-0.dll
api-ms-win-crt-filesystem-l1-1-0.dll
api-ms-win-crt-heap-l1-1-0.dll
api-ms-win-crt-locale-l1-1-0.dll
api-ms-win-crt-math-l1-1-0.dll
api-ms-win-crt-multibyte-l1-1-0.dll
api-ms-win-crt-runtime-l1-1-0.dll
api-ms-win-crt-stdio-l1-1-0.dll
api-ms-win-crt-string-l1-1-0.dll
api-ms-win-crt-time-l1-1-0.dll
api-ms-win-crt-utility-l1-1-0.dll
Link below is the exe and dll files together:
https://ufile.io/e9htu
here's my code if needed:
main.cpp
#include <QCoreApplication>
#include "macfinder.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MACFinder macFinder;
macFinder.findMAC();
return a.exec();
}
macfinder.h
#ifndef MACFINDER_H
#define MACFINDER_H
#include <QObject>
#include <QNetworkConfiguration>
#include <QNetworkConfigurationManager>
#include <QNetworkInterface>
#include <QNetworkSession>
#include <QDebug>
class MACFinder : public QObject
{
Q_OBJECT
public:
explicit MACFinder(QObject *parent = 0);
void findMAC();
private:
QNetworkConfigurationManager ncm;
QString filterMAC(QList<QNetworkConfiguration> configs);
signals:
void foundMAC(QString MAC);
private slots:
void configurationsUpdateCompleted();
};
#endif // MACFINDER_H
macfinder.cpp
#include "macfinder.h"
MACFinder::MACFinder(QObject *parent) : QObject(parent)
{
}
QString MACFinder::filterMAC(QList<QNetworkConfiguration> configs)
{
qDebug() << "MAC and Index: ";
QString MAC;
int index;
QNetworkConfiguration nc;
foreach(nc,configs)
{
QNetworkSession networkSession(nc);
QNetworkInterface netInterface = networkSession.interface();
QString debugStr = QString::number(netInterface.index())
+ " | " + netInterface.humanReadableName() + " | "
+ nc.name() + " | " + netInterface.hardwareAddress();
if(netInterface.hardwareAddress().isEmpty())
{
qDebug() << "--> No MAC: " << debugStr;
continue;
}
if(netInterface.name().isEmpty())
{
qDebug() << "--> NO NAME: " << debugStr;
continue;
}
if(netInterface.index() == 0)
{
qDebug() << "--> NO INDEX: " << debugStr;
continue;
}
if(netInterface.flags() & QNetworkInterface::IsLoopBack)
{
qDebug() << "--> loopBack: " << debugStr;
continue;
}
if(netInterface.flags() & (QNetworkInterface::IsRunning | QNetworkInterface::IsUp))
{
qDebug() << "*** Accepted: " << debugStr;
if(MAC.isEmpty())
{
qDebug() << "setting MAC:" << debugStr;
MAC = netInterface.hardwareAddress();
index = netInterface.index();
}
else
{
if(netInterface.index() < index)
{
qDebug() << "setting MAC:" << debugStr;
MAC = netInterface.hardwareAddress();
index = netInterface.index();
}
else
qDebug() << "index is not lower: " << debugStr;
}
}
}
return MAC;
}
void MACFinder::findMAC()
{
qDebug() << "MACFinder::findMAC | updating all configurations";
connect(&ncm,SIGNAL(updateCompleted()),this,SLOT(configurationsUpdateCompleted()));
ncm.updateConfigurations();
}
void MACFinder::configurationsUpdateCompleted()
{
qDebug() << "MACFinder::configurationsUpdateCompleted";
disconnect(&ncm,SIGNAL(updateCompleted()),this,SLOT(configurationsUpdateCompleted()));
QNetworkConfiguration nc;
QList<QNetworkConfiguration> configs = ncm.allConfigurations(QNetworkConfiguration::Active);
qDebug() << "\nAllConfigs: ";
foreach (nc,configs)
{
qDebug() << nc.identifier() << nc.name() << nc.state();
}
QString MAC = filterMAC(configs);
qDebug() << "\nMAC:" << MAC;
if(MAC.isEmpty())
{
qDebug("no MAC address found");
}
emit foundMAC(MAC);
}
I downloaded your app and analyze it on my computer.
problem is you missing some dlls, your app running without error but not working properly. (qgenericbearer.dll , qnativewifibearer.dll with folder bearer are missing ).
you can use windeploy command to deploy your project.
go to Qt, compiler directory on your OS for example:
C:\Qt\Qt5.7.0\5.7\msvc2013\bin
press Shift+right click mouse then click open command window here
type windeployqt.exe c:\Your app directory for example:
windeployqt.exe C:\Users\Mofrad\Downloads\macfindertest\macFinderTest\macAddressTest.exe
now some dlls will copy to your app directory.
Now try your app again and you'll see it's working.

Communication between Raspberry pi (QT C++) and Arduino (Arduino IDE)

I've been trying for more than a week to communicate from raspberry pi (QT C++) to Arduino (Arduino IDE c++) through a serial port but i keep failing.
I did some searching on google, read the example... and still i didn't succeeded. Ok so the basic thing is that i need to communicate continuously the serial port sent command from Raspberry pi to Arduino. I tried to keep the code as simple as possible.
Initially I'm sending "J" char from raspberry pi (QT C++) to Arduino (Arduino IDE c++) and waiting on that J, to make the LED blink on Arduino. But it doesn't work.. Even I didn't get any sample for interfacing & communicating & sending data raspberry pi (QT C++) to Arduino (Arduino IDE c++). I don't know what is the problem exactly. Kindly help me to solve the issue.
In monitor, 9600 baudrate
I have attached program what I have tried on both side.
main.cpp
#include <iostream>
#include <QIODevice>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QString>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
QSerialPort serialPort;
serialPort.setBaudRate(QSerialPort::Baud9600);
QSerialPortInfo info("ttyUSB0");
qDebug() << "Name : " << info.portName();
qDebug() << "Description : " << info.description();
qDebug() << "Busy:" << info.isBusy();
QSerialPort serial;
serial.setPortName("ttyUSB0");
serial.open(QIODevice::ReadWrite);
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
serial.open(QSerialPort::ReadWrite);
cout<<"Readable :"<<serial.isReadable()<<endl;
cout<<"Writable :"<<serial.isWritable()<<endl<<endl;
if (serial.isOpen() && serial.isWritable())
{
qDebug() << "Is open : " << serial.isOpen() << endl;
qDebug() << "Is writable : " << serial.isWritable() << endl;
qDebug() << "Ready..." << endl;
serial.write("J");
QByteArray ba("J\n");
serial.write(ba);
{
QByteArray ba("J");
serial.write(ba);
serial.flush();
qDebug() << "data has been send" << endl;
serial.close();
}
if (serial.bytesToWrite() > 0)
{
serial.flush();
if(serial.waitForBytesWritten(1000))
{
qDebug() << "data has been send" << endl;
}
}
if(serial.flush())
{
qDebug() << "ok" << endl;
}
qDebug() <<"value sent "<< endl;
serial.close();
}
else
{
qDebug() << "An error occured" << endl;
}
return a.exec();
}
Arduino code:
int led = 13, avlb = 0;
void setup()
{
Serial.begin(9600);
pinMode(led, OUTPUT);
Serial.println("started");
}
void loop()
{
if (Serial.available() > 0)
{
Serial.println("available");
Serial.println(Serial.available());
delay(2000);
digitalWrite(led, HIGH);
delay(5000);
if(Serial.read() == 'J')
{
Serial.println("read");
Serial.println(Serial.read());
delay(2000);
digitalWrite(led, LOW);
delay(1000);
}
}
else
{
Serial.println("not available");
delay(1000);
}
}
Output Displayed:
Raspberry qt creator ide o/p:
Name : "ttyUSB0"
Description : "FT232R USB UART"
Busy: false
Readable :1
Writable :1
Is open : true
Is writable : true
Ready...
data has been send
bool QSerialPort::flush(): device not open
value sent
Arduino Ide Output displayed:
started
not available
not available
not available
not available
not available
not available
not available
not available
not available
I would suggest you to read about how Qt event system works. All Qt IODevice derived classes work asynchronously. You need to use QApplication in order to host its object system. After that, you need to change your code so that it's not blocking io thread of QSerialPort.
I usually use readyRead singal or I use waitForBytesWritten and waitForReadReady combination.You should take a look at the QtSerialPort examples. You'll find there several possible implementations depending on your application needs.
You can try this, it will work fine.
#include <QCoreApplication>
#include <iostream>
#include <QSerialPort>
#include <QDebug>
#include <Windows.h>
#include <QElapsedTimer>
using namespace std;
QSerialPort serial;
QElapsedTimer timer;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
serial.setPortName("ttyUSB0");
serial.open(QIODevice::ReadWrite);
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
while(!serial.isOpen()) serial.open(QIODevice::ReadWrite);
if (serial.isOpen() && serial.isWritable())
{
qDebug() << "Serial is open";
QByteArray output;
QByteArray input;
while(true)
{
output = "a";
serial.write(output);
serial.flush();
timer.start();
// Sleep(80);
qDebug() << timer.elapsed();
serial.waitForBytesWritten(100);
serial.waitForReadyRead(100);
if(serial.bytesAvailable()>=18)
input = serial.read(18);
qDebug()<<input;
}
}
return a.exec();
}
The answer to your question is in the following code:
QByteArray ba("J");
serial.write(ba);
serial.flush();
qDebug() << "data has been send" << endl;
serial.close();
After you make serial.flush (), you immediately close the port. It is necessary to wait until the data is really sent. For example, using bool QSerialPort :: waitForBytesWritten (int msecs).

Serial.write crashes program in Qt (C++)

I am attempting to write a command to a serial port that will change my TV input, but when I try to write the necessary command to the port, I get a very strange output.
#include <QCoreApplication>
#include <QSerialPort>
#include <Windows.h>
int set_id = 0;
int fd = -1;
int main(int argc, char *argv[])
{
QCoreApplication app{argc, argv};
int timeInSeconds=0;
while(timeInSeconds>0)
{
printf("%d...\n",timeInSeconds);
Sleep(1000);
timeInSeconds--;
}
QSerialPort serial;
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
serial.setPortName("com3");
serial.open(QIODevice::ReadWrite);
/*char cmd1='x';
char cmd2='b';
int value=20;
char cmd[20];
int len;
if (value >= 0x100)
len = sprintf(cmd, "%c%c %02x %02x %02x\r", cmd1, cmd2, set_id, value>>8, value&255);
else
{
len = sprintf(cmd, "%c%c %02x %02x\r", cmd1, cmd2, set_id, value);
}
serial.write(cmd, len);
*/
char cmdHex[5]="0xc5";
serial.write(cmdHex);
serial.close();
int stall;
scanf("%d",&stall);
//return a.exec();
}
The code is supposed to change the tv input to av. (Starting from HDMI 1) Also, the block that is commented out is my first attempt at sending the command.
You should study the QSerialPort examples shipped with Qt.
There's the terminal project, which is interactive (nice for testing ports), and the cwritersync does what you're trying to do.
Here is the full cwritersync code:
/****************************************************************************
**
** Copyright (C) 2013 Laszlo Papp <lpapp#kde.org>
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtSerialPort/QSerialPort>
#include <QTextStream>
#include <QCoreApplication>
#include <QFile>
#include <QStringList>
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
QCoreApplication coreApplication(argc, argv);
int argumentCount = QCoreApplication::arguments().size();
QStringList argumentList = QCoreApplication::arguments();
QTextStream standardOutput(stdout);
if (argumentCount == 1) {
standardOutput << QObject::tr("Usage: %1 <serialportname> [baudrate]").arg(argumentList.first()) << endl;
return 1;
}
QSerialPort serialPort;
QString serialPortName = argumentList.at(1);
serialPort.setPortName(serialPortName);
int serialPortBaudRate = (argumentCount > 2) ? argumentList.at(2).toInt() : QSerialPort::Baud9600;
serialPort.setBaudRate(serialPortBaudRate);
if (!serialPort.open(QIODevice::WriteOnly)) {
standardOutput << QObject::tr("Failed to open port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
}
QFile dataFile;
if (!dataFile.open(stdin, QIODevice::ReadOnly)) {
standardOutput << QObject::tr("Failed to open stdin for reading") << endl;
return 1;
}
QByteArray writeData(dataFile.readAll());
dataFile.close();
if (writeData.isEmpty()) {
standardOutput << QObject::tr("Either no data was currently available on the standard input for reading, or an error occurred for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
}
qint64 bytesWritten = serialPort.write(writeData);
if (bytesWritten == -1) {
standardOutput << QObject::tr("Failed to write the data to port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
} else if (bytesWritten != writeData.size()) {
standardOutput << QObject::tr("Failed to write all the data to port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
} else if (!serialPort.waitForBytesWritten(5000)) {
standardOutput << QObject::tr("Operation timed out or an error occurred for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
}
standardOutput << QObject::tr("Data successfully sent to port %1").arg(serialPortName) << endl;
return 0;
}

qt serial receiver missing data

I am trying to read my SerialPort based on the
http://doc.qt.io/qt-5/qtserialport-creadersync-main-cpp.html
example:
QCoreApplication coreApplication(argc, argv);
QTextStream standardOutput(stdout);
QSerialPort serialPort;
QByteArray readData;
serialPort.setPortName("ttyS4");
serialPort.setBaudRate(QSerialPort::Baud9600);
serialPort.setDataBits(QSerialPort::Data8);
serialPort.setParity(QSerialPort::EvenParity);
serialPort.setStopBits(QSerialPort::OneStop);
serialPort.setFlowControl(QSerialPort::NoFlowControl);
if (!serialPort.open(QIODevice::ReadOnly)) {
standardOutput << QObject::tr("Failed to open port") << endl;
return 1;
}
while (serialPort.waitForReadyRead(5000))
readData.append(serialPort.readAll());
qDebug() << readData;
return coreApplication.exec();
I also tried reading Data based on the http://doc.qt.io/qt-5/qtserialport-cwriterasync-example.html example:
Main:
int main(int argc, char *argv[])
{
QCoreApplication coreApplication(argc, argv);
QTextStream standardOutput(stdout);
QSerialPort serialPort;
serialPort.setPortName("ttyS4");
serialPort.setBaudRate(QSerialPort::Baud9600);
serialPort.setDataBits(QSerialPort::Data8);
serialPort.setParity(QSerialPort::EvenParity);
serialPort.setStopBits(QSerialPort::OneStop);
serialPort.setFlowControl(QSerialPort::NoFlowControl);
if (!serialPort.open(QIODevice::ReadOnly)) {
standardOutput << QObject::tr("Failed to open port") << endl;
return 1;
}
SerialPortReader serialPortReader(&serialPort);
return coreApplication.exec();
}
serialPortReader:
SerialPortReader::SerialPortReader(QSerialPort *serialPort, QObject *parent):QObject(parent), m_serialPort(serialPort), m_standardOutput(stdout)
{
connect(m_serialPort, SIGNAL(readyRead()), SLOT(handleReadyRead()));
connect(m_serialPort, SIGNAL(error(QSerialPort::SerialPortError)), SLOT(handleError(QSerialPort::SerialPortError)));
connect(&m_timer, SIGNAL(timeout()), SLOT(handleTimeout()));
m_counter = 0;
m_timer.start(5000);
}
SerialPortReader::~SerialPortReader()
{
}
void SerialPortReader::handleReadyRead()
{ m_counter++;
m_readData.append(m_serialPort->readAll());
qDebug()<< m_serialPort->readAll();
qDebug() << "triggered" << m_counter;
}
void SerialPortReader::handleTimeout()
{
if (m_readData.isEmpty()) {
m_standardOutput << QObject::tr("No data was currently available for reading from port %1").arg(m_serialPort->portName()) << endl;
} else {
m_standardOutput << QObject::tr("Data successfully received from port %1").arg(m_serialPort->portName()) << endl;
m_standardOutput << m_readData << endl;
}
QCoreApplication::quit();
}
void SerialPortReader::handleError(QSerialPort::SerialPortError serialPortError)
{
if (serialPortError == QSerialPort::ReadError) {
m_standardOutput << QObject::tr("An I/O error occurred while reading the data from port %1, error: %2").arg(m_serialPort->portName()).arg(m_serialPort->errorString()) << endl;
QCoreApplication::exit(1);
}
}
But when I send data to this COM port (with same serialPort Settings for Sender), not all of the data is received.
With the MSB-RS232 I can check which data really has been sendet to the port and there is nothing wrong with my sender.
For testing I am sending
main:
QString alpha = "abcdefghijklmnopqrstuvwxyz123456789";
handler.writetoPort(alpha);
handler.cpp:
void SerialHandler::writetoPort(QString x)
{
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QByteArray encodedVar = codec->fromUnicode(x);
writetoPort(encodedVar);
}
void SerialHandler::writetoPort(const QByteArray x)
{
serial.write(x);
serial.waitForBytesWritten(-1);
}
The result of this is the output:
abyz123456789 or abcdklmnopqrstuvwxyz123456789 or abcdefghijklm or ...
It's always different.
Does anyone have a clue what is going on here?
Thank you for reading my long post.
--added 17.07--
This might be mandatory for my problem:
The code has to run on a microprocessor.
CPU: Atmel -AT91SAM9X25 - ARM926(ARMv5) - 400MHz
RAM: 32 MB
Linux Kernel Version: 3.9.0
QT Version: 5.4.1 (cross compiled)
both the async and sync example are working perfectly fine on my Windows PC.
Maybe this will help
void SerialPortReader::handleReadyRead()
{
m_counter++;
while (m_serialPort->bytesAvailable())
{
m_readData.append(m_serialPort->readAll());
}
qDebug()<< m_readData;
qDebug() << "triggered" << m_counter;
}
I tried the exact same Projekt on a different Board and everything works smoothly.
I think the COM Port of the old Board might have been damaged.
Will mark this as resolved but I can't tell what the true problem really was.