1. You may try the following sketch:
#include "RTClib.h"
byte prSec = 0;
RTC_DS1307 rtc; //RTC_DS3231 rtc; //user data type RTC_DS3231 variable rtc or object
DateTime nowDT;
//char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
void setup ()
{
Serial.begin(115200);
rtc.begin();
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
//rtc.adjust(DateTime(2021, 12, 31, 11, 59, 57));//set date-time manualy:yr,mo,dy,hr,mn,sec
}
void loop ()
{
showTime();
timeDelay();//1-sec interval of time display; this time delay comes form DS3231 itself
}
//===================================================
void showTime()
{
nowDT = rtc.now(); //nowDT hold Date and Time
//---------------------------
byte myHour = nowDT.hour(); //myHour holds Hour of time of daya
Serial.print(myHour); //12:58:57 12:4:56
Serial.print(':');
//-------------------------------------------------
byte myMin = nowDT.minute(); //to show leading zero of minute
if (myMin < 10)
{
Serial.print('0');
}
Serial.print(nowDT.minute()); Serial.print(':');
//--------------------------------------------------
byte mySec = nowDT.second();
if (mySec < 10)
{
Serial.print('0');
}
Serial.println(mySec);//(nowDT.second(), DEC);
}
//---------------------------------------------
void timeDelay()
{
prSec = bcdSecond(); //current second of RTC
while (bcdSecond()== prSec)// != 1 )
{
;
}
prSec = bcdSecond(); //delay(1000);
}
byte bcdSecond()
{
nowDT = rtc.now();
if (nowDT.second() == 0 )
{
return 0;
}
else
{
return nowDT.second();
}
}
2. You may also try the following sketch.
#include <Wire.h>
#define dsAddress 0x68
void setup()
{
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(dsAddress); //24 Hours Clock Set
Wire.write(0x00); //address of Second Register is put into Address Counter of RTC
Wire.write(0x12); //data for Sec Register-12
Wire.write(0x58); //data for Min Register (58)
Wire.write(0x23); //data for Hours Register (23): 24 Hours Time: 23:47:12
Wire.endTransmission();
}
void loop()
{
showTime();
delay(1000); //just for the Serial Monitor
}
void showTime()
{
Wire.beginTransmission(dsAddress);
Wire.write(0x00); //address of Second Register is put into Address Counter of RTC
Wire.endTransmission();
Wire.requestFrom(dsAddress, 3);
byte bcdSeconds = Wire.read();
bcdSeconds = bcdSeconds & 0b01111111;
byte bcdMinutes = Wire.read();
byte bcdHours = Wire.read();
Serial.print((bcdHours>>4)& 0b00000011); Serial.print(bcdHours&0b00001111);Serial.print(':');
Serial.print(bcdMinutes>>4); Serial.print(bcdMinutes & 0b00001111);Serial.print(':');
Serial.print(bcdSeconds>>4);Serial.println(bcdSeconds & 0b00001111);
}