I've been trying to set up a project in such in a way that I can comment/uncomment one line and switch between displaying on a 16x2 LCD or displaying on the Serial monitor.
Rather than littering my code with #ifdef SERIAL ... #else and writing two sets of instructions for everything, I've been using the Arduino Streaming library: GitHub - janelia-arduino/Streaming: Streaming C++-style Output with Operator << and I'm having some success!
This for example works great:
#define LCD_ROWS 2
#define LCD_COLS 16
#define LCD_ADDR 0x27
#include "Streaming.h"
#include "LiquidCrystal_I2C.h"
LiquidCrystal_I2C lcd(0x27, 16, 2);
// #define SERIAL_DISPLAY_OVERRIDE
#ifdef SERIAL_DISPLAY_OVERRIDE
#define DISPLAY Serial
#else
#define DISPLAY lcd
#endif
#define BAUDRATE 115200
class Foo {
public:
const char * name;
int value;
void display(Print& p) {
p << name << " " << value;
}
Foo(const char * name, int value)
: name(name), value(value) { }
};
void setup() {
Serial.begin(BAUDRATE);
lcd.init();
lcd.backlight();
Foo foo("Test", 69);
foo.display(DISPLAY);
}
void loop() { }
Simply comment or uncomment #define SERIAL_DISPLAY_OVERRIDE
My issue comes when I want to do the same thing but instead of printing on the same line, I want the name and value printed on two lines. The streaming lib supports endl but the LiquidCrystal lib does not.
Are there any thoughts on how I might achieve this?
I have a kind of hacky attempt here that seems to work is there a way to actually get << endl << to work?
#define LCD_ROWS 2
#define LCD_COLS 16
#define LCD_ADDR 0x27
#include "Streaming.h"
#include "LiquidCrystal_I2C.h"
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define SERIAL_DISPLAY_OVERRIDE
#ifdef SERIAL_DISPLAY_OVERRIDE
#define DISPLAY Serial
#else
#define DISPLAY lcd
#endif
#define BAUDRATE 115200
Print& endLine() {
#ifdef SERIAL_DISPLAY_OVERRIDE
DISPLAY << endl;
#else
DISPLAY.setCursor(0,1);
#endif
return DISPLAY;
}
class Foo {
public:
const char * name;
int value;
void display(Print& p) {
#ifndef SERIAL_DISPLAY_OVERRIDE
lcd.clear();
lcd.setCursor(0,0);
#endif
p << name; endLine() << value;
}
Foo(const char * name, int value)
: name(name), value(value) { }
};
void setup() {
Serial.begin(BAUDRATE);
lcd.init();
lcd.backlight();
Foo foo("Test", 69);
foo.display(DISPLAY);
}
void loop() { }
Because I can't use: p << name << endl << value;