Timed method

Hi, I was wondering if it exists some way to tell the Arduino "If this method takes too long, break it and go further, and tell me you don't have the supposed results"

And with "for too long" i mean a measure of time.

To be more specific I'm messing with the ethernet shield, and I want my little buddy to connect to a different server if the first one takes too long to answer (or if its answer is too long...)

thanks in advance!

Hi, I was wondering if it exists some way to tell the Arduino "If this method takes too long, break it and go further, and tell me you don't have the supposed results"

You can write a function that does something until it succeeds (by whatever measure you define success) OR until a certain time has elapsed.

To be more specific I'm messing with the ethernet shield, and I want my little buddy to connect to a different server if the first one takes too long to answer (or if its answer is too long...)

In this case, you just have to wait for the existing function to time out. It will eventually, but it might take longer than you want.

If you knew how to change that time limit, you wouldn't need to be asking this question. As it is not a trivial change, and the change risks breaking other stuff, you should simply have the Arduino connect to a more reliable server.

If the code is just like this:

requestStuff();
while (haventReceivedStuff());

you could change it to this:

requestStuff();
unsigned long beginTime = millis();
while (haventReceivedStuff() && millis() - beginTime < 10000);

or, if you want to be notified of the failure:

requestStuff();
bool timedOut = false;
unsigned long beginTime = millis();
while (haventReceivedStuff()) {
  if (millis() - beginTime < 10000) {
    timedOut = true;
  }
}

...which is essentially Paul's first suggestion.

Thank you very much... you are right, without further complications this is the way to go go...

This did the trick...

requestStuff();
unsigned long beginTime = millis();
while (haventReceivedStuff() && millis() - beginTime < 10000);

However since i was looking for a solution I ended up reading about the whatchdog, and it seems a great feature! Especially for ethernet applications which are not new to "hangs"...
However I didn't find anything really clear about it. So here is the question: is it safe to enable it on an Arduino UNO board with unmodified bootloader? Will it be possible to disable it in case of reset? Someone says that when a reset occurs the WDT remain enabled to the lowest timing (15 ms) and so there isn't enough time even to load the bootloader (and consequently to launch the sketch) with the consequence of an infinite reset loop. Is this the case of the UNO board?

Thanks a lot for your help and patience.

Using the watchdog timer to reset the Arduino is akin to using a sledge hammer to swat flies. It it ALWAYS better to address the problem causing the need to reset, instead of resetting.

Understood, thank you for your precious help!