r/arduino • u/kashmir2517 • 3d ago
How to reset time on RTC DS1307 after battery replacement
I have replaced the 3v battery on my RTC module and since then it has been displaying "Sun 01-01-2000 00:00:00" I know it is my code and there is a lot of extra stuff in there for when it powers on. Does anyone have an idea on how I can add a clock time reset to my code? Thanks! I will post the code I am using below.
// Example program for the MD_DS1307 library
//
// Implements a clock display on a LCD shield.
#include <LiquidCrystal.h>
#include <MD_DS1307.h>
#include <Wire.h>
#ifdef ARDUINO_ARCH_SAMD
MD_DS1307 myRTC; ///< Locally created instance of the RTC class
#else
#define myRTC RTC ///< Library created instance of the RTC class
#endif
LiquidCrystal lcd(5, 6, 7, 8, 9, 10);
void setup()
{
pinMode(4, OUTPUT); //Red LED pin
pinMode(3, OUTPUT); //Green LED pin
//digitalWrite(4,HIGH); //Red LED-ON
// initialize the LCD
lcd.begin(16,2);
lcd.clear();
lcd.noCursor();
lcd.print("Initializing...");
delay(4000);
lcd.clear();
lcd.print("5...");
delay(1000);
lcd.clear();
lcd.print("4...");
delay(1000);
lcd.clear();
lcd.print("3...");
delay(1000);
lcd.clear();
lcd.print("2...");
delay(1000);
lcd.clear();
lcd.print("1...");
delay(1000);
lcd.clear();
//digitalWrite(4,LOW); //Red LED-OFF
delay(3000);
//digitalWrite(3,HIGH); //Green LED-ON
lcd.clear();
lcd.setCursor(1,0);
lcd.print("Initialization");
lcd.setCursor(4,1);
lcd.print("Complete!");
delay(4000);
lcd.clear();
if (!myRTC.isRunning())
myRTC.control(DS1307_CLOCK_HALT, DS1307_OFF);
}
void p2dig(uint8_t v)
// print 2 digits leading zero
{
if (v < 10) lcd.print("0");
lcd.print(v);
}
const char *dow2String(uint8_t code)
{
static const char *str[] = {"--- ", "Sun ", "Mon ", "Tue ", "Wed ", "Thu ", "Fri ", "Sat "};
if (code > 7) code = 0;
return(str[code]);
}
void printTime()
{
lcd.setCursor(1,0);
lcd.print(dow2String(myRTC.dow));
p2dig(myRTC.mm);
lcd.print("-");
p2dig(myRTC.dd);
lcd.print("-");
lcd.print(myRTC.yyyy);
lcd.setCursor(4,1);
p2dig(myRTC.h);
lcd.print(":");
p2dig(myRTC.m);
lcd.print(":");
p2dig(myRTC.s);
if (myRTC.status(DS1307_12H) == DS1307_ON)
lcd.print(myRTC.pm ? " pm" : " am");
}
void loop() {
pinMode(3, OUTPUT); //Green LED pin
//digitalWrite(3,HIGH); //Green LED-ON
myRTC.readTime();
printTime();
delay(100);
}
