blinking LED on the serial command

Hello everyone,
I need to figure out how to make blink a LED on a serial command.
In fact I would like something like this:

void setup() {                
  pinMode(13, OUTPUT);   
  Serial.begin(9600);  
}

void blink(){
  digitalWrite(13, HIGH);   // set the LED on
  delay(1000);                 // wait for a second
  digitalWrite(13, LOW);   // set the LED off
  delay(1000);
  blink();
}

void off(){
  digitalWrite(13, LOW);
}

void loop () {
  int r = Serial.read ();
  if (r == 100) blink ();
  if (r == 101) off ();
}

But it goes in an infinite loop when i start function "blink" beacuse the recursion call itself every time.

i need to use a thread to this thing?

thanks :slight_smile:

p.s. Sorry for my english

The loop function is called in an endless loop. So, if instead of reading serial data every time, you only read data when it was available, you'd eliminate overwriting the value in r every time.

Look at the Serial.available() function.

And, r should be a global variable.

Then, if there is no new value for r, the old value would remain, and blink() or off() would be called again. There is no reason for blink() to call itself. And, as you've discovered, plenty of reasons for it not to call itself.