Streaming

Streaming C++-style Output with Operator <<

Note: Streaming 5 is now Arduino 1.0 compatible.

New users sometimes wonder why the “Arduino language” doesn’t provide the kind of concatenation or streaming operations they have become accustomed to in Java/VB/C#/C++, etc.

// This doesn't work in Arduino.  Too bad.
lcd.print("The button was pressed " + counter + " times");

Meanwhile, experienced programmers chafe at having to synthesize streams with clumsy blocks of repetitive code like this:

lcd.print("GPS #");
lcd.print(gpsno);
lcd.print(" date: ");
lcd.print(day);
lcd.print("-");
lcd.print(month);
lcd.print("-");
lcd.println(year); // ugh!!

The Streaming library gives you the option of compressing those into “insertion style” code that, if not exactly the same, is reminiscent of the concatenation above:

lcd &lt;&lt; "GPS #" &lt;&lt; gpsno &lt;&lt; " date: " &lt;&lt;
    day &lt;&lt; "-" &lt;&lt; month &lt;&lt; "-" &lt;&lt; year &lt;&lt; endl;

This library works for any class that derives from Print:

Serial &lt;&lt; "Counter: " &lt;&lt; counter;
lcd &lt;&lt; "Temp: " &lt;&lt; t.get_temperature() &lt;&lt; " degrees";
my_pstring &lt;&lt; "Hi Mom!" &lt;&lt; endl;

With the new library you can also use formatting manipulators like this:

Serial &lt;&lt; "Byte value: " &lt;&lt; _HEX(b) &lt;&lt; endl;
lcd &lt;&lt; "The key pressed was " &lt;&lt; _BYTE(c) &lt;&lt; endl;

This syntax is familiar to many, is easy to read and learn, and, importantly, consumes no resources. (Because the operator functions are essentially just inline aliases for their print() counterparts, no sketch gets larger or consumes more RAM as a result of their inclusion.)

I hope someday that this simple template will become part of the Arduino core as a stylistic option to writing series of prints. In the meanwhile, I use it in every sketch I build now!

Download

The latest version of Streaming is available at Streaming5.zip.

Version

You can get the current version number of the library by inspecting STREAMING_LIBRARY_VERSION.

Page last updated on July 31, 2024 at 8:06 am
115 Responses → “Streaming”

  1. wea

    12 years ago

    wow !great library, and very very useful more power to you ! u help a lot of people like


  2. Daniel

    12 years ago

    hi,
    would it be possible to include this snippet in a future release in Streaming.h ?
    it only appends a carriage return instead of CR,LF ( as endl) some hardware only want a carriage return as an end of message sentinel and get upset if they get a line feed as well.

    enum _CarriagReturnCode { crl };

    inline Print &operator <<(Print &obj, _CarriagReturnCode arg)
    { obj.print("\r"); return obj; }
    "


  3. Mikal

    12 years ago

    @Daniel,

    Good thought–I think about it.

    M


  4. matt

    12 years ago

    I wanna send a command to an rfid reader/writer and i need an explination of how to do it, the data sheet: http://www.elechouse.com/elechouse/images/product/13.56MHZ_RFID_Module/13.56MHZ_RFID_Manual.pdf

    Can someone cook up some example code? THANKS GUYS! YOU’RE AWESOME!


  5. Mikal

    12 years ago

    @matt,

    It’s an ordinary 5V TTL Serial device. I think there’s lots of sample code out there for RFID reader/writers, aren’t there?


  6. Arend

    12 years ago

    :D Really great! They should put this in the standard Arduino environment!


  7. Rob Tillaart

    11 years ago

    Hi Mikal,

    Looks good! A small trick to get a leading zero (e.g. in a time string)

    int h = 14;
    int m = 6
    Serial << ((h<10)?"0":"") << h << ":" << ((m<10)?"0":"") << m << endl;

    it would be nice to have something parametrised like

    Serial << ZERO(hour,2) << ":" << ZERO(minute,2) << endl;

    Serial << ZERO(money, 4) << endl;


  8. Rob Tillaart

    11 years ago

    addition, to fill output with some char

    struct _FILL
    {
    char ch;
    int len;
    _FILL(char c, int l): ch(c), len(l)
    {}
    };

    inline Print &operator <<(Print &obj, const _FILL &arg)
    { for (int i=0; i< arg.len; i++) obj.write(arg.ch); return obj; }

    examples
    Serial << _FILL('=', 20) << endl;

    int table[10] = {5,10,4,6,8,12,6,5,3,2};
    for (int i=0; i<10; i++)
    {
    Serial << _FILL('*', table[i]) << endl;
    }


  9. Rob Tillaart

    11 years ago

    see also – http://arduino.cc/forum/index.php/topic,131283.0.html

    struct _TIME
    {
    uint8_t hour;
    uint8_t minu;
    uint8_t sec;
    _TIME(uint8_t h, uint8_t m, uint8_t s): hour(h), minu(m), sec(s)
    {}
    };

    inline Print &operator <<(Print &obj, const _TIME &arg)
    { obj.print(((arg.hour<10)?"0":"")); obj.print(int(arg.hour));
    obj.print(((arg.minu<10)?":0":":")); obj.print(int(arg.minu));
    obj.print(((arg.sec<10)?":0":":")); obj.print(int(arg.sec));
    return obj; }

    Not optimized but might be useful


  10. tony

    11 years ago

    Hey,

    Thanks for this nice library, serial communication works just fine, but i have a problem with printing messages on lcd. Im using LiquidCrystal from arduino standard lib in order to get lcd to work, and yours “steaming” for communicate with it. How can i clear the screen using your library? Also how can i set cursor in custom line/row. In LiquidCrystal im using lcd.clear(), lcd.setCursor (x,y) etc.

    Thanks in advance.
    tony


  11. Wakt

    11 years ago

    Good work. I always wondered why something like this wasn’t included in the first place considering how useful and relatively standard it in nowadays.


  12. Albert

    11 years ago

    I found that << endl is not the same as << "\n". With endl I can't read the serial monitor output to Excel. endl generates an unknown character.


  13. Mikal

    11 years ago

    Rob–

    I quite agree. Thanks for the suggestion.

    Mikal


  14. Mikal

    11 years ago

    @tony,

    The Streaming library isn’t smart enough to know about every possible target device. But that’s ok. For lcd, just do lcd.clear() like usual, then use streaming to write to the lcd. lcd << "Hello!";


  15. Mikal

    11 years ago

    @Albert,

    endl in Streaming-land is “\r\n”, which I think is generally more useful. Apparently not in this case, though. I’m surprised Excel doesn’t like it though. Hmm.. Thanks.


  16. Albert

    11 years ago

    Dear Mikal,
    Please can you add examples of setting the digits / precision?
    For instance, this works fine:
    pString << _FLOAT(floatblabla, 1); // precision = 1 digit

    Best regards

    Albert van Dalen


  17. Mikal

    11 years ago

    @Albert,

    Good idea…!


  18. omar

    11 years ago

    Hi, Im having errors while using this library, how do you get it to work after download?

    Im trying to print a message followed by a single variable and get this error:
    Single_Stepper_Motor_Control:63: error: no match for ‘operator<<' in 'Serial << ("Front Speed: ")'

    The syntax Im using is as follows, if Im mistaken please advice:
    Serial << "Front Speed: " << time;


  19. Mikal

    11 years ago

    @omar,

    It seems like that should work. Are you including streaming.h?


  20. omar

    11 years ago

    I copied the library to the libraries of IDE for arduino, dont know if there is any other thing that I should do.


  21. Mikal

    11 years ago

    I mean, did you add the

    #include <Streaming.h>
    

    line at the top of your code?


  22. omar

    11 years ago

    No Mikal I forgot that, I included and its working fine thanks.


  23. Marc

    11 years ago

    When you put the example code for Flash and streaming together into one code. Some functions from each library don’t work anymore (endl, etc…)
    why ?


  24. Mikal

    11 years ago

    @Marc,

    Can you give an example?


  25. Anthrolume

    11 years ago

    Hi Mikal,

    Great stuff. I used this on my Anthrolume project, and now I’m refitting that project with a Maple instead of the Arduino Mega I used originally. You’ll be glad to know that Streaming.h works perfectly as-is on the Maple! :-)


  26. omar

    11 years ago

    Can this library send a clear line or reset line or clear screen to the serial monitor of the arduino IDE?


  27. Frank

    11 years ago

    Excellent!
    I enhanced the library with some of the ideas in the comments
    I even stumbled across a small omission – _FLOAT was not in the keywords file
    I also enhanced the example sketch
    I’ be happy to share what I have so far


  28. a

    10 years ago

    // This doesn’t work in Arduino. Too bad.
    lcd.print(“The button was pressed ” + counter + ” times”);

    // However, this does work in Arduino:
    lcd.print(“The button was pressed ” + String(counter) + ” times”);


  29. Mikal

    10 years ago

    @a,

    Very true (although you couldn’t do that back when this article was first written).

    However, I am not in favor of using Strings in these scenarios. In fact I never use String at all in any of my code. It’s just too unpredictable to use dynamic memory in a processor with 2K of RAM.


  30. Helmi

    10 years ago

    Nice,
    How about using below function :
    char buffer[23];

    sprintf(buffer,”Time : %d : %d : %d”,hours,minutes,second);

    Serial.print(buffer);


  31. Mikal

    10 years ago

    @Helmi–

    sprintf is a great tool, but doesn’t work in two cases I know of. First of all, on avr-gcc the %f formatter for floating point numbers simply isn’t implemented, presumably to save space. Secondly, there are some cases where you actually have to pass a Stream or Print object to a library function and sprintf can’t behave as a Stream object. Thanks.


  32. se

    10 years ago

    Hello, How would I use streaming to write to an SD card? Thank you, Steve


  33. ElEspanol

    10 years ago

    Hi, I can not get work this example. I understand it that it stores the result in a String (char? or whatever) instead of printing it to somewhere. Is this correct?

    my_pstring << "Hi Mom!" << endl;

    So, please, how can I get it work? The other like lcd << "Hi Mom!" << endl; or Serial << "Hi Mom!" << endl; work well


  34. Mikal

    10 years ago

    Yes, that example should “print” the value “Hi Mom!” to my_pstring. What issues are you having?


  35. ElEspanol

    10 years ago

    #include <Streaming.h>
    String my_pstring="";
    void setup() {
    Serial.begin(9600);
    my_pstring << "Hi Mom!" << endl;
    Serial.println(my_pstring);
    }
    
    void loop() {}
    

    Errores:
    Arduino: 1.5.7 (Windows XP), Board: “Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)”

    sketch_oct03b.ino: In function ‘void setup()’:
    sketch_oct03b.ino:6:12: error: no match for ‘operator<<' (operand types are 'String' and 'const char [8]')
    sketch_oct03b.ino:6:12: note: candidates are:
    In file included from sketch_oct03b.ino:1:0:
    D:\Arduino\libraries\Streaming/Streaming.h:33:15: note: template Print& operator<<(Print&, T)
    inline Print &operator <<(Print &stream, T arg)
    ^
    D:\Arduino\libraries\Streaming/Streaming.h:33:15: note: template argument deduction/substitution failed:
    sketch_oct03b.ino:6:15: note: cannot convert 'my_pstring' (type 'String') to type 'Print&'
    In file included from sketch_oct03b.ino:1:0:
    D:\Arduino\libraries\Streaming/Streaming.h:54:15: note: Print& operator<<(Print&, const _BYTE_CODE&)
    inline Print &operator <<(Print &obj, const _BYTE_CODE &arg)
    ^
    D:\Arduino\libraries\Streaming/Streaming.h:54:15: note: no known conversion for argument 1 from 'String' to 'Print&'
    D:\Arduino\libraries\Streaming/Streaming.h:73:15: note: Print& operator<<(Print&, const _BASED&)
    inline Print &operator <<(Print &obj, const _BASED &arg)
    ^
    D:\Arduino\libraries\Streaming/Streaming.h:73:15: note: no known conversion for argument 1 from 'String' to 'Print&'
    D:\Arduino\libraries\Streaming/Streaming.h:91:15: note: Print& operator<<(Print&, const _FLOAT&)
    inline Print &operator <<(Print &obj, const _FLOAT &arg)
    ^
    D:\Arduino\libraries\Streaming/Streaming.h:91:15: note: no known conversion for argument 1 from 'String' to 'Print&'
    D:\Arduino\libraries\Streaming/Streaming.h:102:15: note: Print& operator<<(Print&, _EndLineCode)
    inline Print &operator <<(Print &obj, _EndLineCode arg)
    ^
    D:\Arduino\libraries\Streaming/Streaming.h:102:15: note: no known conversion for argument 1 from 'String' to 'Print&'


  36. ElEspañol

    10 years ago

    Got it. The secret was to include the Pstring class

    Thx.


  37. Mark

    9 years ago

    Is there a documentation file showing detailing all of the functionality/formatting/usage? I see the use of “endl”; is there documentation listing this and other key words?


  38. Mikal

    9 years ago

    @Mark, “endl” is borrowed from C++. It simply means “end of line”. I think that’s about the only “special” formatting stuff in this library.


  39. Adam

    9 years ago

    I like this library a lot as it provides familiar syntax :) To get it to work under 1.6.4 I had to create a file called “library.properties” and populate it with the following:

    name=Streaming
    version=5
    author=Arduino
    maintainer=Mikal Hart
    sentence=Streaming C++-style Output with Operator <<
    paragraph=Streaming C++-style Output with Operator <<
    category=Language
    url=http://arduiniana.org/libraries/streaming/
    architectures=*

    Hope this helps, and thanks Mikal! :)

11 Trackbacks For This Post
  1. WiFly Shield Ruining Your Weekend? | Mike Newell

    […] Download the Streaming library. […]

  2. ATUP » Concatenation on Arduino

    […] just found the Steaming library which allows you concatenate your strings using […]

  3. Contributed chipKIT™ Libraries | chipKIT™ Development Platform

    […] not ported Streaming Lib Maintainer Page […]

  4. Contributed chipKIT Libraries | chipKIT Development Platform

    […] not ported Streaming Lib Maintainer Page […]

  5. Wifi shield configuration from SD card | chipKIT Development Platform

    […] Streaming  http://arduiniana.org/libraries/streaming/ […]

  6. arduino教程:从arduino发送格式化文本和数字 | 机器人哥

    […] 或者用C++一样的流式输出,由MIKAL HART写的库: […]

  7. How to use infrared remote in your project | My Robot Lab

    […] Here is an example that prints out the decoded hexadecimal number of the received IR signal (if possible), and the protocol that the IR signal used: First of all, install the Streaming library at http://arduiniana.org/libraries/streaming/. […]

  8. Building an Android frontend - Page 2

    […] is the sensor value. I know the << isn't normal Arduino stuff, it's part of the streaming library Reply With Quote vBulletin.events.SkimlinksActivate.subscribe(function() […]

  9. Google Play Music Internet Radio (Raspberry Pi and Arduino) -Use Arduino for Projects

    […] will also need some additional Arduino libraries before the script will compile, namely Streaming, CmdMessenger and Encoder. Once theese are in your libraries folder you should be good to […]

  10. Tema 6 – Comunicaciones con Arduino (3) | Aprendiendo Arduino

    […] Streaming: http://arduiniana.org/libraries/streaming/ […]

  11. Google Play Music Internet Radio (Raspberry Pi and Arduino) -Arduino for Projects

    […] will also need some additional Arduino libraries before the script will compile, namely Streaming, CmdMessenger and Encoder. Once theese are in your libraries folder you should be good to […]

Leave a Reply