After a coffee and a little movement... I've decided that functions related to setting a cursor position have no place interfering with printing or clearing the screen. And so I've changed the usage to be something I feel is much better suited (and less hassle, to be fair):
"CenterAlign.h" (That should and will be split into .h and .cpp)
#ifndef CENTER_ALIGN_H
#define CENTER_ALIGN_H
/*
Ironed out with some aide from 'gfvalvo' and 'J-M-L':
https://forum.arduino.cc/t/conditional-based-on-variable-type/925410/
*/
#ifndef LCD_COLS
#define LCD_COLS 16
#endif
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 double& d, uint8_t dec = 2) {
char buffer[17] = {'\n'};
return strlen(dtostrf(d, 0, dec, buffer));
}
template<typename T>
size_t centerMinus(T t) {
return (LCD_COLS / 2) - (getCharLength(t) / 2.f);
}
template<typename T>
size_t centerMinus(T t, uint8_t dec) {
return (LCD_COLS / 2) - (getCharLength(t, dec) / 2.f);
}
#endif
And an example: (Note! #define LCD_COLS has to come before the include "CenterAlign.h" or it will default to 16 cols)
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define LCD_COLS 16
#include "CenterAlign.h"
void setup() {
Serial.begin(115600);
lcd.init();
lcd.backlight();
lcd.clear();
/*
Usage: centerMinus(Variable);
For floats/doubles... centerMinus(Variable, decimalPlaces);
decimalPlaces defaults to 2.
*/
// Uncomment for test cases
String x = "Centered";
lcd.setCursor(centerMinus(x), 0);
lcd.print(x);
// char* x = "Centered";
// lcd.setCursor(centerMinus(x), 0);
// lcd.print(x);
// char x[] = "Centered";
// lcd.setCursor(centerMinus(x), 0);
// lcd.print(x);
// lcd.setCursor(centerMinus(F("Centered")), 0);
// lcd.print(F("Centered"));
// lcd.setCursor(centerMinus("Centered"), 0);
// lcd.print("Centered");
// int y = 22222;
// lcd.setCursor(centerMinus(y), 1);
// lcd.print(y);
// int y = -22222;
// lcd.setCursor(centerMinus(y), 1);
// lcd.print(y);
// Float and double defaults to 2 decimal places unless specified like so
float y = 49.8765432;
lcd.setCursor(centerMinus(y, 7), 1);
lcd.print(y, 7);
// double y = 49.8765432;
// lcd.setCursor(centerMinus(y), 0);
// lcd.print(y);
}
void loop() { }