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 << "GPS #" << gpsno << " date: " <<
    day << "-" << month << "-" << year << endl;

This library works for any class that derives from Print:

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

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

Serial << "Byte value: " << _HEX(b) << endl;
lcd << "The key pressed was " << _BYTE(c) << 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 2, 2013 at 9:31 pm
95 Responses → “Streaming”

  1. Mikal

    2 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?


  2. Arend

    2 years ago

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


  3. Rob Tillaart

    2 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;


  4. Rob Tillaart

    2 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;
    }


  5. Rob Tillaart

    2 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


  6. tony

    2 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


  7. Wakt

    1 year 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.


  8. Albert

    1 year 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.


  9. Mikal

    1 year ago

    Rob–

    I quite agree. Thanks for the suggestion.

    Mikal


  10. Mikal

    1 year 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!”;


  11. Mikal

    1 year 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.


  12. Albert

    1 year 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


  13. Mikal

    1 year ago

    @Albert,

    Good idea…!


  14. omar

    1 year 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;


  15. Mikal

    1 year ago

    @omar,

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


  16. omar

    1 year ago

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


  17. Mikal

    1 year ago

    I mean, did you add the

    #include <Streaming.h>
    

    line at the top of your code?


  18. omar

    1 year ago

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


  19. Marc

    1 year 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 ?


  20. Mikal

    1 year ago

    @Marc,

    Can you give an example?


  21. Anthrolume

    1 year 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! :-)


  22. omar

    1 year ago

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


  23. Frank

    1 year 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


  24. a

    1 year 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”);


  25. Mikal

    1 year 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.


  26. Helmi

    9 months ago

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

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

    Serial.print(buffer);


  27. Mikal

    9 months 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.


  28. se

    2 months ago

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


  29. ElEspanol

    1 month 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


  30. Mikal

    1 month ago

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


  31. ElEspanol

    1 month 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&'


  32. ElEspañol

    1 month ago

    Got it. The secret was to include the Pstring class

    Thx.

13 Trackbacks For This Post
  1. New Streaming Library | Arduiniana

    [...] Streaming [...]

  2. RobotGrrl.com » Blog Archive » Arduino SSC32 Library

    [...] SSC32 library uses the Arduiniana Streaming library. Be sure to download and install it into your sketches/libraries/ [...]

  3. Arduino net connected clock tells weather not time

    [...] were used; PStringto handle parsing the incoming website, Flash for memory management, and Streaming for easier coding. Source:Sean Carney’s Weather Clock/ Please post a comment or leave a [...]

  4. Pin Sleep Xbee with Arduino Host | Ponderings

    [...] Streaming C++ style Output – print and println gets to be a pain after a while [...]

  5. WiFly Shield Ruining Your Weekend? | Mike Newell

    [...] Download the Streaming library. [...]

  6. ATUP » Concatenation on Arduino

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

  7. Contributed chipKIT™ Libraries | chipKIT™ Development Platform

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

  8. Contributed chipKIT Libraries | chipKIT Development Platform

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

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

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

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

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

  11. 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/. [...]

  12. 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() [...]

  13. 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 [...]

Leave a Reply