I am using the following code to display a digital clock using my arduino uno:
#include <Time.h>
#include <LiquidCrystal.h>
#define TIME_MSG_LEN 11 // time sync to PC is HEADER followed by Unix time_t as ten ASCII digits
#define TIME_HEADER 'T' // Header tag for serial time sync message
#define TIME_REQUEST 7 // ASCII bell character requests a time sync message
// T1262347200 //noon Jan 1 2010
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int clockSet = 0;
void setup()
{
Serial.begin(9600);
lcd.begin(16, 2);
}
void loop()
{
if(clockSet == 0)
{
if(Serial.available() )
{
processSyncMessage();
clockSet = 1;
}
}
digitalClockDisplay();
delay(1000);
}
void digitalClockDisplay()
{
lcd.setCursor(1,0);
lcd.print(hour());
lcdPrintDigits(minute());
lcdPrintDigits(second());
}
void lcdPrintDigits(int digits){
// utility function for digital clock display: prints preceding colon and leading 0
lcd.print(":");
if(digits < 10)
lcd.print('0');
lcd.print(digits);
}
void processSyncMessage() {
// if time sync available from serial port, update time and return true
while(Serial.available() >= TIME_MSG_LEN ){ // time message consists of header & 10 ASCII digits
char c = Serial.read() ;
Serial.print(c);
if( c == TIME_HEADER ) {
time_t pctime = 0;
for(int i=0; i < TIME_MSG_LEN -1; i++){
c = Serial.read();
if( c >= '0' && c <= '9'){
pctime = (10 * pctime) + (c - '0') ; // convert digits to a number
}
}
setTime(pctime); // Sync Arduino clock to the time received on the serial port
}
}
}
Most of this is out of the example code for the time.h library. The problem is the clock loses about 2 minutes each day (i.e. it is 2 minutes slower than my computer clock). Any ideas on why this might be? I have cut down the code as much as I can such that it only calls processSyncMessage once (the first time I send the time to the arduino). I thought maybe executing processSyncMessage every time through the loop was slowing it down but that doesn't seem to be the case. Maybe I should change the delay to delayMicroseconds()?
Thanks.