Great!
Well, in that case, I think this might be mission accomplished? The center-aligned LCD print.
Can I please throw this to the wolves to see if it survives?
I've added comments where needed to explain, and you'll need to simply uncomment the test cases (mostly a variable and print statement).
I'll probably pull this into a .h file if/when I want to use it.
A small gripe is the truncation favouring extra space on the left, I'd rather it be on the right.
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
size_t getCharLength(const char* cp) {
return strlen(cp);
}
size_t getCharLength(String &s) {
return s.length();
}
size_t getCharLength(const __FlashStringHelper *ifsh) {
return strlen_P(reinterpret_cast<PGM_P>(ifsh));
}
size_t getCharLength(const int& i) {
char buffer[17];
return sprintf(buffer, "%d", i);
}
size_t getCharLength(const float& f, uint8_t dec = 2) {
char buffer[17] = {'\n'};
return strlen(dtostrf(f, 0, dec, buffer));
}
size_t getCharLength(const double& d, uint8_t dec = 2) {
char buffer[17] = {'\n'};
return strlen(dtostrf(d, 0, dec, buffer));
}
template<typename T>
void LCDPrint(T t, uint8_t row, bool clear = false) {
if (clear) lcd.clear();
lcd.setCursor(8 - (getCharLength(t) / 2), row);
lcd.print(t);
}
template<typename T>
void LCDPrint(T &t, uint8_t p, uint8_t row, bool clear = false) {
if (clear) lcd.clear();
lcd.setCursor(8 - (getCharLength(t, p) / 2), row);
lcd.print(t, p);
}
void setup() {
Serial.begin(115600);
lcd.init();
lcd.backlight();
lcd.clear();
// Usage:
// LCDPrint(Variable, LCD Row, Bool To Clear LCD);
// Or...
// LCDPrint(Variable, Decimal Places, LCD Row, Bool To Clear LCD);
// Bool to clear LCD is defaulted to false;
// String x = "TEN CHARS!";
// LCDPrint(x, 0);
// char* x = "TEN CHARS!";
// LCDPrint(x, 0);
// char x[] = "TEN CHARS!";
// LCDPrint(x, 0);
// LCDPrint(F("TEN CHARS!"), 0, true);
// LCDPrint("TEN CHARS!", 0);
// int x = 22222;
// LCDPrint(x, 0);
// int x = -22222;
// LCDPrint(x, 0);
// Float and double defaults to 2 decimal places unless specified.
// float x = 49.8765432;
// LCDPrint(x, 0);
// Unfortunately the overload is ambiguous, so if we specify the decimals
// we HAVE to specify true/false to clear the LCD.
// float x = 49.8765432;
// LCDPrint(x, 3, 0, false);
// double x = 49.8765432;
// LCDPrint(x, 0);
}
void loop() { }