Unsolved Error with QserialPort
-
Hi,
i am using a function call "AvancoAut()" belong to class AvancoAtrasoAut. This function write a bytearray in my serial port. When i call this function inside a for in other class, the first time the serial write the valour, but when this funtcion is called again, for exemple for two loops, for the second time, the serial does not wirte.
The code is:
avancoatrasoaut.h#ifndef AVANCOATRASOAUT_H
#define AVANCOATRASOAUT_Hclass AvancoAtrasoAut
{
public:
AvancoAtrasoAut();
~AvancoAtrasoAut();
void AvancoAut();
};#endif // AVANCOATRASOAUT_H
avancoatrasoaut.cpp
#include "avancoatrasoaut.h"
#include <QDebug>
#include <QSerialPort>
#include <QSerialPortInfo>
#include "global.h"
#include "QString"QSerialPort serial;
AvancoAtrasoAut::AvancoAtrasoAut()
{}
AvancoAtrasoAut::~AvancoAtrasoAut()
{}
void AvancoAtrasoAut::AvancoAut()
{
QString y;
y.setNum(passo);
QByteArray x(y.toStdString().c_str());
x = "c" + x;
serial.setPortName("COM2");
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);if(serial.open(QIODevice::ReadWrite)){ serial.write(x);} else{ qDebug() << serial.errorString();} return;
}
The class this function is called.
posicionadorautomatico1.cppfor(m=0;m<qtd_avan;m++) { posicao=posicao+deltang; //função(avanço) x.AvancoAut(); LeituradePotencia2 leipot; leipot.setModal(true); leipot.exec(); }
i did not post the entire code of this last class, but inside this for, the function x.AvancoAut just write one time and when needs to write the second time, the program returns "unknow error".
Thanks!
-
Not sure if i think correctly but i think the error is coused by serial.open() call, first time you can open the port of course but the second time it is already opened so it returns error.
Try moving QSerialPort *serial into header file, createing object in the constructor of the class like serial= new QSerialPort(this) and implementing your serialOpen(), serialWrite(/QbyteArray mayby?/) functions, it will be much clearer i guess. -
Hello michelson,
thanks for the tip, help me a lot. Indeed, i was trying to open the serial port two times, so after i write the bytearray to serial port, i used the QSerialPort::waitForBytesWritten() and after that i close the port. It is not the way you told me, but it worked. Thanks again.