Hier ist mal einfacher Code um eine Zahl auf konstant "width" Zeichen Breite zu formatieren. Optional rechtsbündig
void prettyPrint(long value, int width, bool rightadjust = false);
void setup()
{
Serial.begin(9600);
}
void loop()
{
prettyPrint(10, 3);
prettyPrint(100, 3);
prettyPrint(1000, 3);
prettyPrint(10, 4);
prettyPrint(100, 4);
prettyPrint(1000, 4);
prettyPrint(10, 5);
prettyPrint(100, 5);
prettyPrint(1000, 5);
prettyPrint(10, 6, true);
prettyPrint(100, 6, true);
prettyPrint(1000, 6, true);
prettyPrint(10, 4, true);
prettyPrint(100, 4, true);
prettyPrint(1000, 4, true);
Serial.println();
delay(2000);
}
void prettyPrint(long value, int width, bool rightadjust)
{
long val = (value < 0) ? value * -1 : value;
if (value < 0) width--;
if (!rightadjust) Serial.print(value);
unsigned long num = 10;
for (int i = 0; i < width - 1; i++)
{
if (val < num) Serial.print(' ');
num = num * 10;
}
if (rightadjust) Serial.print(value);
Serial.println(); //diese Zeile bei LCDs entfernen!
}
Es gibt da auch Keulen wie sprintf(), aber das ist bei einer Zahl Overkill
Anmerkung:
Der Arduino Parser macht wieder mal Scheiße beim Erzeugen der automatischen Funktions-Prototypen und erkennt den Default Parameter nicht korrekt. Deshalb der explizite Prototyp am Anfang.