Tired of typing Serial.print() over and over? Try this template hack.

I posted this on reddit and I feel like there may be a few users here that would also enjoy it. I modified this example to include spaces and newline characters, but you can adjust this to suit your needs.

// Template for printing
template<typename T>
void printT(T value) {
  Serial.println(value);
}
template<typename T, typename... Args>
void printT(T firstValue, Args... args) {
  Serial.print(firstValue);
  Serial.print(" ");
  printT(args...);
}

This template hack just calls "Serial.print" for each new argument of the printT function. That means you can say "printT(value1, value2, " ")" and so on. All you need to do is include the two templates in your program. The best part is that this just uses the native "Serial.print" command.
Here's an example:

I am really fond of the Streaming.h library. Usage is like

#include <Streaming.h>
:
:
Serial << F("Value: ") << value << " (" << _HEX(value) << ")" << endl;

It has a lot of helper functions to mangle the data before printing. E.g width, number base, ...

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.