-->
Page 1 of 1

Wrapper function for Serial.printf()

PostPosted: Tue May 17, 2022 1:07 am
by neo2001
I've successfully used Serial.prinft() for my debug output. For now, I've put the line between #ifdef DEBUG_MODE ... #endif preprocessor directives.

To make it more clear and less cluttered reading the code, I decided to write a simple wrapper function for Serial.printf(). This function looks like this:

Code: Select alldebugPrintf(const char *format, ...) {
  if (DEBUG_MODE) {
    va_list args;
    va_start(args, format);
    Serial.printf(format, args);
    va_end(args);
  }
}


The problem with this is, that the text (first argument of printf()) gets printed fine, but all the values/placeholders that where replaced/formatted before are now replaced with a arbitrary number.

Example:

Instead of something like this

Code: Select allTaillights (TL)       : 254 (received value: 254)
Sidelights (SL)       : 0 (received value: 0)
Reversing Lights (REV): 0 (received value: 0)
Indicator L (IL)      : 0 (received value: 0)
Indicator R (IL)      : 0 (received value: 0)


I get this:

Code: Select allTaillights (TL)       : 1073741664 (received value: 1073741648)
Sidelights (SL)       : 1073741664 (received value: 1073741648)
Reversing Lights (REV): 1073741664 (received value: 1073741648)
Indicator L (IL)      : 1073741664 (received value: 1073741648)
Indicator R (IL)      : 1073741664 (received value: 1073741648)


All I want is to pass the argument given to my own function directly to Serial.printf(), but there seems to be the problem. I've searched all over the Web, but can only find solutions that already look basically like what I'm a doing.

Any ideas?

Re: Wrapper function for Serial.printf()

PostPosted: Wed May 18, 2022 12:43 am
by JurajA
there is no version of Serial.printf for va_list

Re: Wrapper function for Serial.printf()

PostPosted: Fri May 20, 2022 8:03 am
by Inq720
I'm assuming you just want an easy way to toggle debugging info on/off. I use this to do that purpose...

Code: Select all// Put these at the top of your ino/cpp files. 
#define dbg(f, ...) (void)0
// Uncomment when you want to show debug info.
//#define dbg(f, ...) Serial.printf(f, ## __VA_ARGS__)

// Example usage.
void loop()
{
    u32 now = millis();
    dbg("This is the current millis = %u\n", now);
    delay(1000);
}