PDA

View Full Version : while loop question..



b1
25th May 2009, 03:31
G'Day,

I have the following code ( which works ) but during run time can potentially crash. It uses the qextserialport library.



recflag = true;
rec = serialPort->bytesAvailable();
while ( recflag )
{
serialPort->read( retdata, 60 );
if ( retdata[39] == 0x4F && retdata[40] == 0x04B )
{
sendwin->label_2->setText("Switch "+swnum+" succeeded" );
recflag = false;
}
else
{
errorlist << "\nswitch "+swnum+" failed";
sendwin->label_2->setText( "Switch "+swnum+" FAILED" );
errorflag = true;
recflag = false;
}
}


If no data is seen on the serial port, the app just sits there until something comes in or I crash the app. My question is how can I implement a timer of, say 500ms, to break the loop. I have tried using a timer but they don't seem to trigger the slot.

Any suggestions would be greatly appreciated.

Thank, B1.

wagmare
25th May 2009, 06:18
G'Day,
If no data is seen on the serial port, the app just sits there until something comes in or I crash the app. My question is how can I implement a timer of, say 500ms, to break the loop. I have tried using a timer but they don't seem to trigger the slot.

Any suggestions would be greatly appreciated.

Thank, B1.

simple .. u have the answer in your code ...
declare the recFlag globally in your .h file


privare:
bool recFlag;
QTimer *timer;

in .cpp


recFlag = false;
timer = new QTimer();
timer->setSingleShot(true);
connect(timer, SIGNAL(timeout()), this, SLOT(breakLoop()));
timer->start(500);




void MyWidger:: breakLoop(){
recFlag = true;
}



see the blocking fortune client example :
http://doc.trolltech.com/4.5/network-blockingfortuneclient-fortunethread-cpp.html

they are using your method only ...

i missed that ... dont forget to call your function again in breakLoop()


while ( recflag )
{
serialPort->read( retdata, 60 );
}

b1
25th May 2009, 07:50
Thanks for the prompt reply, wagmare.

I will follow your suggestion and will also look at the example code.

Thanks again, b1.

PaceyIV
25th May 2009, 10:48
serialPort->read( retdata, 60 );
Reads at most 60 bytes from the device into retdata, but retdata can be smaller then 60 byte.

You should use the return value of the function so you can check if retdata[39] and retdata[40] exists before access to them.