How to get time next 45 minute from DS3231?

I want to get time next 45 minute. I read data from DS3231 like this code.

void loop () {
  DateTime now = RTC.now();
  DateTime next;

  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(' ');
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute()+45, DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();

  delay(3000);
}

The output is

2021/5/6 11:79:23
2021/5/6 11:79:26
2021/5/6 11:79:29

The minutes of output is more than 60 minute. How to get time next 45 minute from DS3231?

Hello,

Edit: if you use this library GitHub - adafruit/RTClib: A fork of Jeelab's fantastic RTC Arduino library then look at the example datecalc

There is more than one way to do this. Here is how I would do it:

DateTime now = RTC.now();
byte hh = now.hour();
byte mi = now.minute();
byte ss = now.second():

// print the current time
Serial.print("Current time: ");
Serial.print(hh);
Serial.print(':');
Serial.print(mi);
Serial.print(':');
Serial.println(ss);

// now add 45 minutes
mi += 45;

// now do the carries
// 60 minutes make an hour
if (mi >= 60) {
  mi -= 60;
  hh++;
}
// 24 hours make a day
if (hh >= 24) {
  hh -= 24;
  // if you care about the date,
  // you will need more code to handle the date
}

// print the resulting time
Serial.print("Future time: ");
Serial.print(hh);
Serial.print(':');
Serial.print(mi);
Serial.print(':');
Serial.println(ss);

Yes, that library makes it ridiculously simple:

#include <RTClib.h>

void showDate(const char* txt, const DateTime& dt);

void setup() {
  Serial.begin(115200);
  delay(1000);

  DateTime now{2021, 5, 6, 7, 38, 0};
  showDate("Right Now:", now);
  showDate("45 Minutes from Right Now:", now + 45 * 60UL);
}

void loop() {
}

void showDate(const char* txt, const DateTime& dt) {
  Serial.print(txt);
  Serial.print(' ');
  Serial.print(dt.year(), DEC);
  Serial.print('/');
  Serial.print(dt.month(), DEC);
  Serial.print('/');
  Serial.print(dt.day(), DEC);
  Serial.print(' ');
  Serial.print(dt.hour(), DEC);
  Serial.print(':');
  Serial.print(dt.minute(), DEC);
  Serial.print(':');
  Serial.print(dt.second(), DEC);

  Serial.print(" = ");
  Serial.print(dt.unixtime());
  Serial.print("s / ");
  Serial.print(dt.unixtime() / 86400L);
  Serial.print("d since 1970");
  Serial.println();
}

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.