Adding Streaming (insertion-style) Output

Note that there is an easy to use library version of this here: http://arduiniana.org/libraries/streaming/

If you insert one line to the top of your sketch or in a header file, you can get streaming for free:

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

This allows you to write succinct code like

Serial << "My name is " << name << " and I am " << age << " years old.";

or

Serial << "GPS unit #" << gpsno << " reports lat/long of " << lat << "/" << long;

instead of having to type

Serial.print("My name is ");
Serial.print(name);
Serial.print(" and I am");
Serial.print(age);
Serial.print(" years old.");

or

Serial.print("GPS unit #");
Serial.print(gpsno);
Serial.print(" reports lat/long of ");
Serial.print(lat);
Serial.print("/");
Serial.print(long);

The template line defines the << operator for all classes which derive from Print: Serial, LCD, Ethernet, and others. The insertion syntax is easy to learn and should already be very familiar to C++ users.

The alternate syntax is functionally identical to the series of print calls and consumes no additional RAM or flash resources.

Mikal Hart

Share