Im with @arvid-jense on this one, if you are working on a serious Digital Clock, then you should get the Real Time Clock.
Now if you are learning Arduino and want to play with your LCD Minidisplay and build a clock, you must know some important limitations of the millis() function on this project:
- The mills function will overflow (go back to zero), after
approximately 50 days.
- Your clock will be inexact because the cycles of the Arduino
loop, you will be checking how much mills has passed on each loop.
(it will be lagging ~ 10 seconds each day, so on day 7 you will be one minute late)
- the parameter for millis is an unsigned long, errors may be generated
if a programmer tries to do math with other datatypes such as ints.
That being said
#include <Wire.h>
#include <LiquidCrystal.h>
#define MILLIS_OVERFLOW 34359738
/**
* Clock Variables
*/
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds, minutes, hours;
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
void setup()
{
lcd.begin( 16, 2 );
}
void loop()
{
setClock();
/**
* After set clock now you have 3 int variables with the current time
*/
//seconds
//minutes
//hours
lcd.setCursor ( 0, 1);
lcd.print(millis());
}
void setClock()
{
currentMillis = millis();
/**
* The only moment when currentMillis will be smaller than previousMillis
* will be when millis() oveflows
*/
if (currentMillis < previousMillis){
elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
} else {
elapsedMillis += currentMillis - previousMillis;
}
/**
* If we use equals 1000 its possible that because of the mentioned loop limitation
* you check the difference when its value is (999) and on the next loop its value is (1001)
*/
if (elapsedMillis > 999){
seconds++;
elapsedMillis = elapsedMillis - 1000;
}
if (seconds == 60){
minutes++;
seconds = 0;
}
if (minutes == 60){
hours++;
minutes = 0;
}
if (hours == 24){
hours = 0;
}
previousMillis = currentMillis;
}
Nice tutorial on building an Alarm Clock