Optional parameters

This one may look trivial to the experts, but it took me some time to find (by pure chance) the solution to one of my problems: How to define functions or routines with optional parmeters? Overlaod is the answer!

In fact, it is extremely easy and handy. First, you write your routine/function has you would usually do. The example below blinks a led (Impressive!) and you can decide about the number of blinks, the duration of each blink and the on time ratio.

This will give you something like

void setup(){
  DDRB |=  (1 << PINB5);
}

void loop(){
  blinkLed(500);
  delay(1000);
}

// Functions
void blinkLed(int blinks, int duration, int onTimeRatio) {
  int onTime = int((duration*onTimeRatio)/100);
  int offTime = (duration - onTime);
  for (int i=0; i < blinks; i++) {
    PORTB |=  (1 << PINB5); // Turn led on
    delay(onTime);
    PORTB &= ~(1 << PINB5); // Turn led off
    delay(offTime);
  }
}

But, seriously, are you so much intrested in the on time ratio while blinking a led as an activity indicator? The only thing you have to do is to append the following code to the previous lines

void blinkLed(int blinks, int duration) {
  blinkLed(blinks, duration, 50);
}

Did you notice that we replaced the on time ratio by a fixed value (that we could have read from outside)?

And so on, down a minimal led blinking routine

void blinkLed(int duration) {
  blinkLed(5, duration, 10);
}

void blinkLed() {
  blinkLed(5, 400, 50);
}

What I found very interesting, is that you can also program this type of routine/function (if you are interested in setting the duration as the only parameter)

void blinkLed(int duration) {
  blinkLed(5, duration, 10);
}

Instead of (if you are interested in setting the number of blinks as the only parameter):

void blinkLed(int blinks) {
  blinkLed(blinks, 400, 50);
}

Which means (may be an expert could give more details and references) that the compiler branches to the appropriate routine/function, depending upon the number of parameters that are passed on to it, and on the type of parameter too.

void blinkLed(float onTimeRatio) {
  blinkLed(5, 100, long(onTimeRatio*100));
}

void blinkLed(int onTimeRatio) {
  blinkLed(5, 100, onTimeRatio);
}

void blinkLed(boolean onTimeRatio) {
  if (onTimeRatio) 
    blinkLed(5, 100, 90);
  else
    blinkLed(5, 100, 10);
}

Warning: The compiler may get confused by data types (e.g. int vs long vs boolean) so that it may be necessary to cast values (e.g. (boolean)x, 0.01F, (int)x)

Leave a Reply

You must be logged in to post a comment.