/*
Forum: https://forum.arduino.cc/t/beginner-needs-help-with-debounce-logic/1425853/272
Wokwi: https://wokwi.com/projects/460043180347195393
2026/03/31
ec2021
*/
void setup() {
Serial.begin(115200);
Serial.println("displayCount");
displayCount( 2, 1);
displayCount( 8, 1);
displayCount( 9, 1);
Serial.println("newDisplayCount");
newDisplayCount( 2, 1);
newDisplayCount( 8, 1);
newDisplayCount( 9, 1);
}
void loop() {
// put your main code here, to run repeatedly:
}
void displayCount(byte nDigits, unsigned long Count) {
char countTxt[16]; // specific for this particular 2 line x 16 char LCD
if (nDigits == 9) {
snprintf(countTxt, sizeof countTxt, "%08.9ld", Count); //
}
if (nDigits == 8) {
snprintf(countTxt, sizeof countTxt, "%08.8ld", Count); //
}
if (nDigits == 7) {
snprintf(countTxt, sizeof countTxt, "%08.7ld", Count); //
}
if (nDigits == 6) {
snprintf(countTxt, sizeof countTxt, "%08.6ld", Count); // original six digit counter "%08.6ld"
}
if (nDigits == 5) {
snprintf(countTxt, sizeof countTxt, "%08.5ld", Count); //
}
if (nDigits == 4) {
snprintf(countTxt, sizeof countTxt, "%08.4ld", Count); //
}
if (nDigits == 3) {
snprintf(countTxt, sizeof countTxt, "%08.3ld", Count); //
}
if (nDigits == 2) {
snprintf(countTxt, sizeof countTxt, "%08.2ld", Count); //
}
Serial.println(countTxt);
}
void newDisplayCount(byte nDigits, unsigned long Count) {
char countTxt[16]; // specific for this particular 2 line x 16 char LCD
char formStr[] = "%08.Xld"; // "X" is the placeholder at position 4 (counting from 0 as usual in C/C++)
if (nDigits > 1 && nDigits < 10) {
formStr[4] = '0' + nDigits; // is equal to = 48 + nDigits; but easier to read/understand
snprintf(countTxt, sizeof countTxt, formStr, Count); //
Serial.print(countTxt);
Serial.print('\t');
Serial.println(formStr); // Just to show the effect of changing the char at position 4 in formStr
}
// If nDigits is not in the range 2..9 nothing happens
}