Today I wrote one of my smallest libs ever, but still useful.
The Class calculates the length of something that needs to be printed. Imagine a float or int with an unknown number of digits. Can be used e.g. for right alignment either on serial or any other stream or to position it nicely on a display. An example sketch shows how right alignment can be done.
The Class is called PrintSize, derives from Print and is experimental as it is not tested extensively. Also I want to investigate other applications. I will publish the class on github asap.
//
// FILE: PrintSize1.ino
// AUTHOR: Rob Tillaart
// VERSION: 0.0.1
// PURPOSE: demo printSize
//
// HISTORY:
#include "PrintSize.h"
PrintSize ps;
void setup()
{
Serial.begin(115200);
Serial.println(__FILE__);
Serial.println("Determine length of 10 random numbers and right ");
Serial.println("align the numbers in a table with their sum.");
Serial.println();
uint32_t sum = 0;
for (int i = 0; i < 10; i++)
{
uint32_t rn = random(100000000);
int length = ps.println(rn);
printSpaces(15 - length);
sum += rn;
Serial.println(rn);
}
Serial.print("================ +\n");
int length = ps.println(sum);
printSpaces(15 - length);
Serial.println(sum);
}
void loop()
{
}
void printSpaces(int n)
{
if (n <= 0) return;
while (n)
{
Serial.print(' ');
n--;
}
}
And the library (no there is nothing missing, this is all
//
// FILE: printSize.h
// AUTHOR: Rob Tillaart
// VERSION: 0.1.0
// PURPOSE: Class that determines printSize
// DATE: 2017-12-09
// URL:
//
// Released to the public domain
//
#ifndef PrintSize_h
#define PrintSize_h
#include "Print.h"
#define PRINTSIZE_VERSION "0.1.0"
class PrintSize: public Print
{
public:
PrintSize() {};
size_t write(uint8_t c) { return 1; }
};
#endif
// -- END OF FILE --