Restarting a function?

Hi everyone! I always wondered if it would be possible to use something like the "MsTimer2" for resetting a particular function in the arduino. Below I included a simple example in which I would like to reset the "printer" function.

Would something like this be a possibility?

#include <MsTimer2.h>
int time_counter;

void setup () { 
  Serial.begin(9600);
  Serial.println("Setting up...");
  MsTimer2::set(8000, time_checker);
  MsTimer2::start();
}

void loop () 
{
  printer ();
}


void time_checker(){
  Serial.println("I WOULD START FROM THE BEGINNING NOW... ");

  //HERE: command to restart "printer" function
}


void printer () 
{
 int counter = 0;

 for (int printloop= 0; printloop < 10; printloop++)
  {
    counter = counter + 1;
    Serial.print("Hello World ");
    Serial.println(counter);
    delay(1000);        
  }

  Serial.println("Done");
  delay(1000);
}

Basically no.
You would need something inside the printer function that looked at a flag and caused it to reset itself. That flag would be set by the timer routine and reset once the function saw it set.

You probably want a Watchdog Timer.
http://tushev.org/articles/arduino/item/46-arduino-and-watchdog-timer

There is a difference between "restarting" a function (like you have illustrated) which calls Serial.print() many times and "restarting" the Serial.print() command itself if it does not complete fast enough.

All you need for the type of function you have is the coding concept illustrated by the "blink without delay" sketch. Record the millis() before starting the function and every iteration compare the latest value of millis() with the stored value. When the difference becomes too great terminate the loop without marking the print job complete. Then your loop() function can call the printing function again and again until it runs through and marks the print job complete.

I have no suggestions for problems within the Serial.print() function, but I have never experienced any.

...R

You guys are awesome! Thank you for the great feedback... This definitely gives me a solid place to start working from :slight_smile: