I've been trying to get the time on my arduino uno to sync correctly to my computer pc, i even changed the time in my computer to see if i could get the hour to change with it on the arduino, i had no luck.
My problem is that the time on the arduino is always about 30-45 seconds slower than the PC time, however eventually (and only sometimes) the arduino will catch up with the pc and then pass it. (almost seems like it sets the wrong time, but the DS1307 is clocking time faster than the pc is). I know that the 1307 is incredibly unreliable, however, i also feel like maybe its something with my coding. I've already replaced the RTC with another brand (1307 for both) and they seem to have the same problem
#include <Wire.h>
#include "RTClib.h"
#include <LiquidCrystal.h>
#include <TimeAlarms.h>
#include <Time.h>
RTC_DS1307 RTC;
LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7);
int motorPin = 2;
int lastHour = 23;
int lastMinute = 59;
bool feedPet = false;
unsigned long feedTime = 0;
unsigned long lastPrintTime = 0;
struct FeedTime{
int hour, minute;
};
FeedTime amFeed = {10, 0}; // i.e. 10:00am
FeedTime pmFeed = {17,30}; // i.e. 5:30pm
void setup ()
{
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
lcd.begin(16, 2);
Wire.begin();
RTC.begin();
if (! RTC.isrunning())
{
lcd.println("RTC NOT Running!");
RTC.adjust(DateTime((__DATE__), (__TIME__)));
}
}
void loop ()
{
DateTime now = RTC.now();
FeedTime currentTime;
currentTime.hour = now.hour();
currentTime.minute = now.minute();
if((currentTime.minute != lastMinute) && (((currentTime.hour == amFeed.hour) && (currentTime.minute == amFeed.minute)) || ((currentTime.hour == pmFeed.hour) && (currentTime.minute == pmFeed.minute))))
{
feedTime = millis();
feedPet = true;
}
lastMinute = currentTime.minute;
if (feedPet)
{
turnFeeder();
}
if (millis() - lastPrintTime > 1000UL)
{
lcd.setCursor(0, 0);
char nowDate[24] = "";
sprintf(nowDate, "DATE: %02d/%02d/%d", now.month(), now.day(), now.year());
lcd.print(nowDate);
// display the time
lcd.setCursor(0, 1);
char nowTime[24] = "";
sprintf(nowTime, "Time: %02d:%02d:%02d", now.hour(), now.minute(), now.second());
lcd.print(nowTime);
lastPrintTime = millis();
}
}
void turnFeeder(void)
{
static bool pinState = true;
if (millis() - feedTime < 60000UL) // 60 second(s)
{
if (pinState)
{
digitalWrite(motorPin, HIGH);
pinState = false;
}
}
else
{
digitalWrite(motorPin, LOW);
pinState = true;
feedPet = false;
}
}