C++ library StringStream (for Serial.print)

There is something amazingly cool in C++ programs: using streams for output. It's a lot easier than in C when you use printf-like functions.

Eg: You've got 2 variables in your code, you'd like to preview them:

var_1=42; var_2=47;
std::cout << "Variable 1 = " << var_1 << endl << "Variable 2 = " << var_2 << endl;

will give on a terminal:

Variable 1 = 42
Variable 2 = 47

Now imagine you want to do the same thing on the arduino, via Serial.print:

Serial.print("Variable 1 = ");
Serial.println(var_1, DEC);
Serial.print("Variable 2 = ");
Serial.println(var_2, DEC);

A bit longer..

As the Arduino software is C++ compatible, it could be possible to include some of the standard libraries, to enable this..

Franky, you may be interested in this thread: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1231224786

Ha! Yes, I still include this line in every sketch I use at home:

template<class T> inline Print &operator <<(Print &obj, T arg) { obj.print(arg); return obj; }

I agree it's pretty darn cool! :slight_smile:

Mikal

It's probably just because I'm not used to seeing it, but I find

std::cout << "Variable 1 = " << var_1 << endl << "Variable 2 = " << var_2 << endl;

to be almost unreadable. All those "<" characters confuse me - I prefer the long winded

Serial.print("Variable 1 = ");
Serial.println(var_1, DEC);
Serial.print("Variable 2 = ");
Serial.println(var_2, DEC);

Does anyone know if there's any difference in how many bytes each compiles to?

Andrew

Does anyone know if there's any difference in how many bytes each compiles to?

There is no difference, the same machine code would be produced by a stream version or seperate print statements.

There is no difference, the same machine code would be produced by a stream version or seperate print statements.

Thanks. I'll stick with the long-winded version then, which now I come to think of it is quite odd since I'm quite happy to write something like

pattern = ++pattern % numPatterns

I guess it really does come down to what you're used to (e.g. "where do the curly braces go?").

Andrew

Yeah, indeed that's cool for long serial data transmission, or for Terminal purpose using Serial Monitor...

I was first thinking about a printf function, with variable arguments, but as Arduino handles c++, streams are definitely a better way..

I will try this stuff, thanks guys!