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
113 Responses → “Streaming”

  1. Mikal

    11 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

    11 years ago

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


  3. 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;


  4. 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;
    }


  5. 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


  6. 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


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


  8. 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.


  9. Mikal

    11 years ago

    Rob–

    I quite agree. Thanks for the suggestion.

    Mikal


  10. 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!”;


  11. 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.


  12. 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


  13. Mikal

    11 years ago

    @Albert,

    Good idea…!


  14. 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;


  15. Mikal

    11 years ago

    @omar,

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


  16. 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.


  17. Mikal

    11 years ago

    I mean, did you add the

    #include <Streaming.h>
    

    line at the top of your code?


  18. omar

    11 years ago

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


  19. 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 ?


  20. Mikal

    11 years ago

    @Marc,

    Can you give an example?


  21. 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! :-)


  22. 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?


  23. 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


  24. 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”);


  25. 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.


  26. 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);


  27. 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.


  28. se

    9 years ago

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


  29. ElEspanol

    9 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


  30. Mikal

    9 years ago

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


  31. ElEspanol

    9 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&'


  32. ElEspañol

    9 years ago

    Got it. The secret was to include the Pstring class

    Thx.


  33. 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?


  34. 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.


  35. Adam

    8 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! :)


  36. Mikal

    8 years ago

    Many thanks @Adam!!


  37. yair

    8 years ago

    hi Mikal, please add it to the lib repository so it appears in the manage lib at arduino IDE. its just to good. there is an alternative called printEx which is buggy on my tests.


  38. Bill

    6 years ago

    streaming.cpp seems to be missing from the streaming5.zip file download. Thanks


  39. Raf

    6 years ago

    How to print ” sign ?


  40. Mikal

    6 years ago

    @Bill, Streaming is an unusual library: no .cpp!


  41. Solar_eta

    6 years ago

    Presumably this will also work instead of client.print(“blabla”); I assume that you need to open an Ethernet client first.
    Similarly for dataFile.print(“blabla”); once you’ve opened the file on the Sd cars with if (dataFile.open(fileName, O_WRITE | O_APPEND )) { etc.


  42. Mikal

    6 years ago

    @Solar_eta, I would expect it to. Let us know…!


  43. Hans Roark

    6 years ago

    Keep up the good work!


  44. Mike_Malaysia

    5 years ago

    Dear Mikal.
    Thank you for this. It’s fantastic.
    Did you made a “cin >>” equivalent header?? If so that fantastic^2
    (and if you did, what could one find it?)


  45. Ted Timmons

    5 years ago

    Looks like using _DEC(254) instead of char(254) takes up ~400 bytes of flash, as long as I replace all references to one or the other. On the other hand, using << streaming syntax (again, universally, instead of lcd.print and lcd.write) saved me about the same number of bytes and maybe some memory too. Neat.


  46. Raju

    5 years ago

    Hi I have the following code which also includes the Streaming library which i have downloaded from Streaming5.zip. I have used the Arduino Zero device to test the AnalogReadFast code. But the streaming library seems not helping to print out the serial print on the serial monitor. Can you please help me why the following code is not giving any serial print output on the serial monitor?

    Code:
    #include
    #include
    #include
    #include “avdweb_AnalogReadFast.h”

    const byte adcPin = A0;

    void setup()
    { Serial.begin(9600);
    while (!Serial);
    Serial << "\nanalogRead_10bit us1 analogRead_12bit us2 analogReadFast_10bit us3 analogReadFast_12bit us4" << endl;
    for (int i = 0; i < 10; i++) testAnalogRead();
    }

    void testAnalogRead()
    { static Stopwatch stopwatch(micros);
    //delay(1000);

    stopwatch.start();
    int adc1 = analogRead(adcPin); // default resolution 10bit 425us on SAMD21
    stopwatch.stop(); int t1 = stopwatch.interval;

    analogReadResolution(12);
    stopwatch.start();
    int adc2 = analogRead(adcPin); // 425us on SAMD21
    stopwatch.stop(); int t2 = stopwatch.interval;

    analogReadResolution(10);
    stopwatch.start();
    int adc3 = analogReadFast(adcPin); // 23us on SAMD21
    stopwatch.stop(); int t3 = stopwatch.interval;

    analogReadResolution(12);
    stopwatch.start();
    int adc4 = analogReadFast(adcPin); // 24us on SAMD21
    stopwatch.stop(); int t4 = stopwatch.interval;

    Serial << "adc1, t1, adc2, t2, adc3, t3, adc4, t4 << endl";
    //Serial << adc1, t1, adc2, t2, adc3, t3, adc4, t4;
    analogReadResolution(10); // restore default
    }

    void loop()
    {
    }

    Note: This code compiles in the Arduino Zero but does not give the serial output

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

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

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

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

  16. Arduino :: TOOLS OPTIMALISASI ARDUINO (file presentasi .ppt) | Fajar Ridikc

    [...] šArduiniana Streaming, library untuk streaming [...]

  17. Arduino – Language and Libraries – eletx

    [...] Streaming– a method to simplify print statements [...]

Leave a Reply