Friday, February 24, 2012

Cleaner Arduino Coding with Streaming

Arduino Serial.Print() and Serial.Write() instructions multiply like bunnies in applications that use serial output for debugging or to drive serial displays. If only related instructions, variables and strings could be neatly packaged for serial output using a single instruction...Turns out that they can, and with zero code overhead. All that's required is the Streaming library from Arduiniana.org.

Once you copy the Streaming folder into your Arduino Libraries directory, you can #include <Streaming.h> into your programs and go from this:

Serial.Print("x= ") ;
Serial.Print(varX) ;
Serial.Print(" y= ");
Serial.Print(varY);
//ad nauseum


to this:

Serial<<"x= "<<varX<<" y= "<<varY;

Slick, eh? Below is an example that drives a BPI-216 serial LCD or GLO-216Y/G serial OLED. (Although the GLOs have a larger, more extensive instruction set, they understand a subset of LCD instructions, too.)

/*
Streaming Example for BPI-216 Serial LCD 
 (Will run on GLO-216Y/G, too, thanks to 
 limited BPI emulation.)
 
 Arduiniana.org offers an Arduino library that enables C++
 style "streaming" notation for serial output. Streaming 
 really helps tighten up multi-part Prints by allowing 
 you to combine multiple strings, chars, bytes and 
 variables into a single line that get 'funneled' into 
 the serial object by a series of << symbols. 
 */

#include <SoftwareSerial.h>  // New SoftSerial, Arduino v1.0+
#include <Streaming.h>

#define rxPin 255       // Not used, so set to invalid pin #
#define txPin 3         // Hook BPI/BPK SER input to Arduino pin 3.
#define inverted 1     // Set serial-output polarity to inverted

//BPI Clear-Screen instruction, plus a redundant Position-to-0
//instruction for timing purposes. 
#define CLS "\xFE\x01\xFE\x80"
//BPI Go-To-Start-of-Line-2 instruction. 
#define L2 "\xFE\xC0"

/* 
Set up a new serial output using the pin definitions above. Note the  
"inverted," which instructs SoftwareSerial to output BPI/BPK-compatible 
inverted-TTL serial (like RS-232, but without the +/- voltage swing).
 */
SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin, inverted);

// The Serial dot-Print method handles all sorts of data, including 
// automatic conversion of floats to strings (with two digits after
// the decimal point). 
float pi = 3.14159; // Print prints floats.
int two = 2 ;  // Print also prints ints (as does <<) 

void setup()  {
  // define pin modes for tx, rx:
  digitalWrite(txPin, LOW);   // Stop bit state for inverted serial
  pinMode(txPin, OUTPUT);
  mySerial.begin(9600);    // Set the data rate
  delay(1000);              // wait.

  // Here's the magical "Streaming" part. The line that follows 
  // replaces seven lines of "mySerial.Print(...)" instructions. 

  mySerial<<CLS <<"Pi is " <<pi <<L2 <<"Good "<<two <<" know.";  
}

void loop() {
  // ...
}

Arduino-compatible serial OLED: $39 at seetron.

No comments:

Post a Comment