RTClib: setting an alarm after retrieving and evaluating current time

I would like to setup the next alarm to 06h00 if the current time is 22h00; otherwise set the alarm to 10 minutes from present time.

I started with the example sketches but this isn't working:

// Set alarm to 10min from present time
// If present time is 22h00, set alarm to 06h00 instead
if (now.hour() == 22 || now.minute() == 0 || now.second() == 0)
{
  if (!rtc.setAlarm1(
        rtc.now() + TimeSpan(0, 8, 0, 0),
        DS3231_A1_Hour //
      )) {
    Serial.println("Error, alarm wasn't set!");
  } else {
    Serial.println("Alarm will happen in 8 hours!");
  }
}
else
{
  if (!rtc.setAlarm1(
        rtc.now() + TimeSpan(0, 0, 10, 0),
        DS3231_A1_Minute //
      )) {
    Serial.println("Error, alarm wasn't set!");
  } else {
    Serial.println("Alarm will happen in 10 minutes!");
  }
}

"isn't working" is the worst description of a problem. How is it not working? Are you getting the error message "Alarm wasn't set" or not? If not, is the alarm actually happing, or not?

Your logic is wrong

if (now.hour() == 22 || now.minute() == 0 || now.second() == 0)

says if hour is 22 OR minute is zero OR second is zero. That statement will evaluate true every minute and every hour and every time you check during the 10pm hour. Not what you want. You want to AND those conditions. Even that is not really that good since if you don't check at exactly 22:00:00, it will fail. The best approach may be to only set the alarm if needed by using a flag. Without the whole sketch, only you can tell.

"isn't working" is the worst description of a problem.

Not the worst, as it did not keep you from objectively helping me on this.

I meant to write &&, not ||.

I also overlooked the condition would fail if it wasn't checked at precisely 22h00 - thank your for the heads up.

Every time my device is powered, if the hour value matches 22, the alarm should be set to 8 hours in the future. Else the alarm should be set to 10min from that moment. (I think that's it)

  // Set alarm to 10min from present time
  // If present hour is 22h, set alarm to 06h00 instead
  Serial.print("now.hour(): ");
  Serial.println(now.hour(), DEC);
  if ( now.hour() == 22 ) {
    if (!rtc.setAlarm1(
          rtc.now() + TimeSpan(0, 8, 0, 0),
          DS3231_A1_Hour //
        )) {
      Serial.println("Error, alarm wasn't set!");
    } else {
      Serial.println("Alarm will happen in 8 hours!");
    }
  }
  else {
    if (!rtc.setAlarm1(
          rtc.now() + TimeSpan(0, 0, 1, 0),
          DS3231_A1_Minute //
        )) {
      Serial.println("Error, alarm wasn't set!");
    } else {
      Serial.println("Alarm will happen in 10 minutes!");
    }
  }

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