When it comes to print numbers most software will print it left-aligned which sometimes looks very ugly. To overcome this, mostly the results get stored in a string and filled with blanks to get the desired length. So you end up with two loops: one filling the string and another counting the digits and adding the blanks.
This is an alternative way to get the result on one go. It was written for 4-digit displays controlled by a TM1637 (of course, you can attach several of them).
const byte N = 4;
// Suppress Leading Zeros:
boolean slz(Display d, byte p, int v) {
boolean isZero;
int div = v / 10;
byte mod = v % 10;
boolean mod0 = mod == 0; // is this digit = 0?
if (p == 1) isZero = mod0; // (at the end)
else isZero = slz(d, p - 1, div); // recursion
// now we start to work:
char c;
if (isZero && mod0 && (p < N) ) c = ' ';
else c = '0' + mod;
write(d, digits[c]);
return isZero && mod0;
}
void writeRight(Display d, int x) {
start(d);
write(d, 0xc0); // Set the first address
boolean dummy = slz(d, N, x);
Stop(d);
}
As you can see, the main program will have to call the writeRight function. This will call slz which is written as a recursive function. It will call itself until it reaches the leftmost position. On its way back, it will check for non-zero values and eventually replace them by blanks. The start- and stop-functions are required to control the TM1637. As an example, you will find an application that prints the lengths of the legs of Pythagorean triangles using three 4-digit displays, each of them controlled by a TM1637.
Aditionally, there is a file which contains a counter running on a 8-digit display controlled by a TM1638.
Warning
In case of limited RAM space please not: due to require space for local variables calling writeRight consumes 104 bytes of memory when driving 8 digits.
And also pushing and popping parameters will take some precious CPU time.
All software is written for the Arduino UNO and not using any libraries at all, so it should not be too complicated to port it to other systems.
Comments
Please log in or sign up to comment.