2

I tried to modify the basic "hello-world" sketch for the LCD that is a part of the examples section in the IDE. I intended to make a countdown timer using the LCD.

The original code simply prints "Hello World" in the first line, and then makes use of the millis() function to print the time elapsed in the next line.

So I tried a simple modification to make it count down from 20. Instead of printing millis()/1000 , I printed 20-millis()/1000, and also added a while() to only print till millis()<=20,000. (so that it does not go beyond 00)

#include <LiquidCrystal.h>


LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  
  lcd.begin(16, 2);
  
  lcd.print("time left");
}

void loop() {
  
  while(millis()<=20000){
    
    lcd.setCursor(0, 1);
    
    lcd.print(20- millis() / 1000);
  }
  

}

It seemed to work till 10. but instead of 9, it printed 90, and likewise 80,70.. for 8,7...etc till 00.

How can I get rid of these extra zeros?

2
  • 5
    lcd.print(' ');
    – Juraj
    May 1, 2021 at 7:04
  • 1
    where do I put this?
    – satan 29
    May 1, 2021 at 7:12

1 Answer 1

6

instead of 9, it printed 90

No, it didn't: it printed “9”. However, it did not erase the previous value before printing “9”. Before printing the 9, the LCD had:

┌────────────────┐
│time left       │
│10              │
└────────────────┘
 ^cursor position

When you printed “9”, that character replaced the “1”, and you end up seeing “90”.

The fix, as pointed out by Juraj, is to add a space after printing the numbers.

An alternative is to prepend a space (or a zero), but only when the number to be displayed is less that 10:

int count = 20 - millis() / 1000;
if (count < 10)
    lcd.print(' ');  // alternatively: '0'
lcd.print(count);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.