Help using Serial.println inside a function

Hi guys, I’ve been trying to do something that is probably really simple but I can’t find anywhere how to properly do it. I basically want to use Serial.println inside a function but am not sure how to pass the arguments to it. Here is what I’m trying to do:

void serialPrint(char* s1, char* s2){
  #ifdef DEBUG_ACTIVE
    Serial.println(s1,s2);
  #endif
}

I’m not sure what the correct syntax is … Serial.println can take one or multiple arguments if I’m not mistaken. Can anyone help me learn how to do this please.

Thanks,

Serial.println() only takes up to two parameters.
The two param version is meant to take a numeric type as first param and a format as second.

So you’d either do

  Serial.print(s1);
  Serial.println(s2);

Or you use Serial.printlnf("%s %s", s1, s2);

1 Like

If you’re just concerned with adding/removing debug code and not the syntax, try something like this. When you have DEBUG_ACTIVE defined, it will compile any debugprint() lines, otherwise they get removed from the compile.

#ifdef DEBUG_ACTIVE
#define debugprint(x) Serial.println(x)
#else
#define debugprint(x)
#endif

oh nice… I’ll use that.

I’m still wondering how to pass 1 or more arguments to a function (that takes one or more arguments like Serial.println) inside a function.

Like in this case:

void serialPrint(char* s1, char* s2){
  #ifdef DEBUG_ACTIVE
    Serial.println(s1,s2);
  #endif
}

I want to be able to use my functions the same way as Serial.println, eg:

serialPrint("print this line");

or

serialPrint(5, HEX);

I’m still not sure what the correct syntax is to do that. But thanks for your help.

Have you seen this post of mine?

The way how Serial.println() does it is via overloading which is a C++ intrinsic feature.
Have a look on the web for the ins and outs of C++.
Or if you want to do it similar to printf(), you could google for "variable argument list"


BTW: Serial.println(s1,s2); won't work as you might expect, hence my previous post.

Yeah, too much trouble. There’s no easy way to #define function(x, …) for variable args functions, or do overloaded syntax. You’d need to define a dbg1(x) and dbg2(x, y) or something.

Thanks for your help… I’ll have to google variable argument lists as you have suggested… I’m not sure how C++ handles that. Some easy saturday night reading :smile:

Variable args are pushed on the stack and you need special functions to access it. Look at va_start(), va_end() and vnsprintf(). vnsprintf is given a pointer to the stack like an array. One valuable resource is the Particle firmware. If you don’t know how something works, check the code. :smile:

Wow, it embeds that. Well, neat.