Hi Team
I am just starting on Arduino and trying to run a simple clock sketch. Facing problem with get pctime and make clock to count. Tried some examples sketches and error persists. Need your help to move forward. Another small point can not display correctly weekday ! Many Thanks in advance for any guidance on what is missed/wrong.
Here is my sketch:
/ Daily alarm using a DS1307 RTC
#include <Wire.h>
#include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
#include <LiquidCrystal.h>
#include <Time.h>
#include <TimeAlarms.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
char *dayOfWeek[] = {"", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
void setup() {
Serial.begin(9600);
setSyncProvider(RTC.get); // the function to get the time from the RTC
if(timeStatus()!= timeSet)
Serial.println("Unable to sync with the RTC");
else
Serial.println("RTC has set the system time");
Alarm.alarmRepeat(06,30,0, Event1); // every day
lcd.begin(16,2);
pinMode(13, OUTPUT);
}
void loop () {
if(Serial.available())
{
time_t t = processSyncMessage();
if(t >0)
{
RTC.set(t); // set the RTC and the system time to the received value
setTime(t);
}
}
clockDisplay();
Alarm.delay(1000);
}
void clockDisplay()
{
char date[15]; // -------------------- RTC Time --------------------
sprintf(date, "%02d/%02d/%4d %dayOfWeek[weekday()]", day(), month(), year(), weekday());
lcd.setCursor(0,0);
lcd.print(date);
char time[9]; // ------------------ Arduino Time -----------------
sprintf(time, "%02d:%02d:%02d", hour(), minute(), second());
lcd.setCursor(4,1);
lcd.print(time);
}
void Event1(){
digitalWrite(13, HIGH); //alarm test output
Alarm.delay(4000);
digitalWrite(13, LOW);
}
/* code to process time sync messages from the serial port */
#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
time_t processSyncMessage() {
// return the time if a valid sync message is received on the serial port.
while(Serial.available() >= TIME_MSG_LEN ){ // time message consists of a header and ten 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
}
}
return pctime;
}
}
return 0;
}