Wake up Arduino Uno from sleep mode by RTC DS3231

Hi everyone,
I intend to make my code that after meet the certain requirement (after the mosfet go to HIGH at first time) then go back to sleep mode but not sure how to. At the moment I use the SQW wake up pin to wake up the device at certain time. Is there any way that I can break the while loop and straight away put my device back to sleep mode when the first time the MOSFET go to HIGH??
Many thanks.

#include <NewPing.h>
#include <RTClibExtended.h>
#include <Wire.h>
#include <LowPower.h>
#include <SD.h>
#include <stdlib.h>
#include <avr/interrupt.h>      // library for interrupts handling
#include <avr/sleep.h>          // library for sleep
#include <avr/power.h>          // library for power control


#define wakePin 2    //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
#define ledPin A0
#define mosfet 9
#define SONAR_NUM 2      // Number of sensors.
#define MAX_DISTANCE 70 // Maximum distance (in cm) to ping.
#define power 8

const int trigPin1 = 4;
const int echoPin1 = 5;
long duration1;
int distance1;

const int trigPin2 = 6;
const int echoPin2 = 7;
long duration2;
int distance2;

RTC_DS3231 rtc;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int interval_sec=10; //An alarm every 10 sec
int i;


void setup () {

  Serial.begin(9600);

  delay(3000); // wait for console opening

  /**RTC**/
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

  /**INTERRUPT**/
  //Set pin D2 as INPUT for accepting the interrupt signal from DS3231
  pinMode(wakePin, INPUT);
  //set mosfet pin to output 
  pinMode(power, OUTPUT);
  pinMode(mosfet, OUTPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(mosfet, LOW);
  //ultrasonic 
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  
  Wire.begin();
  //clear any pending alarms
  rtc.armAlarm(1, false);
  rtc.clearAlarm(1);
  rtc.alarmInterrupt(1, false);
  rtc.armAlarm(2, false);
  rtc.clearAlarm(2);
  rtc.alarmInterrupt(2, false);

  //Set SQW pin to OFF 
  //The output of the DS3231 INT pin is connected to this pin
  //connected to arduino D2 pin for wake-up
  rtc.writeSqwPinMode(DS3231_OFF);

  Serial.println("Initialisation complete.");
  delay(100); //Allow for serial print to complete.
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    /**INTURRUPT**/
    DateTime nextAlarm = now + TimeSpan(0, 0, 0, interval_sec);
    Serial.print("Alarm at:");
    Serial.println(nextAlarm.hour());
    Serial.println(nextAlarm.minute());
    Serial.println(nextAlarm.second());
    rtc.setAlarm(ALM1_MATCH_HOURS, nextAlarm.second(), nextAlarm.minute(), nextAlarm.hour(), 1);   //set your wake-up time here
    rtc.alarmInterrupt(1, true);
    attachInterrupt(0, wakeUp, LOW);       //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW    
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);   //arduino enters sleep mode here
    detachInterrupt(0);                                    //execution resumes from here after wake-up
    //When exiting the sleep mode we clear the alarm
    rtc.armAlarm(1, false);
    rtc.clearAlarm(1);
    rtc.alarmInterrupt(1, false);
  
    while ( now.minute()>0 && now.minute() < 55)
    {
       distance1 = range(trigPin1, echoPin1, power);
       distance2 = range(trigPin2, echoPin2, power);
       
       Serial.print("Distance 1:");
       Serial.print( distance1);
       Serial.print(" Distance 2:");
       Serial.println( distance2);
        
       if(distance1<10 && distance2<10)
       {
        digitalWrite(mosfet, HIGH);
        delay(50);
       }
       else
       {
        digitalWrite(mosfet, LOW);
        delay(50);
       }
            
       digitalWrite(ledPin, HIGH);
       delay(50);
       digitalWrite(ledPin, LOW);
       delay(50);
  
       now = rtc.now();//check time again
    }

}
unsigned long range(byte trigPin, byte echoPin, byte vcc)
  {
    digitalWrite(vcc, LOW);
    delay(50);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);    
    unsigned long duration = pulseIn(echoPin, HIGH);
    digitalWrite(vcc, HIGH);
    delay(100);
    return duration * 0.034 / 2;
    
   }
void wakeUp()        // here the interrupt is handled after wakeup
{
}

Is there any way that I can break the while loop

Yes. That's what the break statement is for.

when the first time the MOSFET go to HIGH??

The Arduino can only read whether an input pin is HIGH or LOW. What is driving the pin is irrelevant.

Hi Paul,
I try to put the break statement right after the microsd card module write the time to the microsd card. However, the system is break while loop and then come back to the while loop but not the sleep mode. Do I make a mistake somewhere?

#include <SPI.h>
#include <NewPing.h>
#include <RTClibExtended.h>
#include <Wire.h>
#include <LowPower.h>
#include <SD.h>
#include <stdlib.h>
#include <avr/interrupt.h>      // library for interrupts handling
#include <avr/sleep.h>          // library for sleep
#include <avr/power.h>          // library for power control

#define LOG_INTERVAL 2000//1s
#define SYNC_INTERVAL 2000

#define wakePin 2    //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
#define ledPin A0
#define mosfet 9
#define SONAR_NUM 2      // Number of sensors.
#define MAX_DISTANCE 70 // Maximum distance (in cm) to ping.
#define power 8
#define chipSelect 10
File logfile;
void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);
  while(1);
}

const int trigPin1 = 4;
const int echoPin1 = 5;
long duration1;
int distance1;

const int trigPin2 = 6;
const int echoPin2 = 7;
long duration2;
int distance2;

RTC_DS3231 rtc;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int interval_sec=10; //An alarm every 10 sec
int i;


void setup () {

  Serial.begin(9600);

  delay(3000); // wait for console opening

  /**RTC**/
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

  /**INTERRUPT**/
  //Set pin D2 as INPUT for accepting the interrupt signal from DS3231
  pinMode(wakePin, INPUT);
  //set mosfet pin to output 
  pinMode(power, OUTPUT);
  pinMode(mosfet, OUTPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(mosfet, LOW);
  //ultrasonic 
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  //SD card 
  Serial.println("Initializing SD card...");
  pinMode(chipSelect, OUTPUT);
  if(!SD.begin(chipSelect))
  {
    error("Card failed or not present");
  }
  Serial.println("Card Initialized.");
  char filename[] = "DATA00.CSV";
  for (uint8_t i = 0; i<100; i++)
  {
    filename[4] = i/10 + '0';
    filename[5] = i%10 + '0';
    if(!SD.exists(filename))
    {
      logfile = SD.open(filename, FILE_WRITE);
      break;
    }
  }
  if(!logfile)
  {
    error("couldnt create file");
  }
  Serial.print("Logging to: ");
  Serial.println(filename);
//////////////////////////////////////////  
  Wire.begin();
  //clear any pending alarms
  rtc.armAlarm(1, false);
  rtc.clearAlarm(1);
  rtc.alarmInterrupt(1, false);
  rtc.armAlarm(2, false);
  rtc.clearAlarm(2);
  rtc.alarmInterrupt(2, false);

  //Set SQW pin to OFF 
  //The output of the DS3231 INT pin is connected to this pin
  //connected to arduino D2 pin for wake-up
  rtc.writeSqwPinMode(DS3231_OFF);

  Serial.println("Initialisation complete.");
  delay(100); //Allow for serial print to complete.
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    /**INTURRUPT**/
    DateTime nextAlarm = now + TimeSpan(0, 0, 0, interval_sec);
    Serial.print("Alarm at:");
    Serial.println(nextAlarm.hour());
    Serial.println(nextAlarm.minute());
    Serial.println(nextAlarm.second());
    rtc.setAlarm(ALM1_MATCH_HOURS, nextAlarm.second(), nextAlarm.minute(), nextAlarm.hour(), 1);   //set your wake-up time here
    rtc.alarmInterrupt(1, true);
    attachInterrupt(0, wakeUp, LOW);       //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW    
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);   //arduino enters sleep mode here
    detachInterrupt(0);                                    //execution resumes from here after wake-up
    //When exiting the sleep mode we clear the alarm
    rtc.armAlarm(1, false);
    rtc.clearAlarm(1);
    rtc.alarmInterrupt(1, false);
  
    while ( now.minute()>0 && now.minute() < 55)
    {
       distance1 = range(trigPin1, echoPin1, power);
       distance2 = range(trigPin2, echoPin2, power);
       
       Serial.print("Distance 1:");
       Serial.print( distance1);
       Serial.print(" Distance 2:");
       Serial.println( distance2);
       //delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL)); 
       if(distance1<10 && distance2<10)
       {
        digitalWrite(mosfet, HIGH);
        delay(50);
        i=0;
       }
       else
       {
        digitalWrite(mosfet, LOW);
        delay(50);
        i=1;
       }
       if (i==0)
       {

       // delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));
        logfile.print('"');
        logfile.print(now.day(), DEC);
        logfile.print("/");
        logfile.print(now.month(), DEC);
        logfile.print("/");
        logfile.print(now.year(), DEC);
        logfile.print("   ");
        logfile.print(now.hour(), DEC);
        logfile.print(":");
        logfile.print(now.minute(), DEC);
        logfile.print(":");
        logfile.print(now.second(), DEC); 
        logfile.print('"');
        logfile.flush();
        logfile.print("\n");
        logfile.close();      
        break;//break the loop and come back to sleep mode
       }
       //flashing LED to shows device is in active mode
       digitalWrite(ledPin, HIGH);
       delay(50);
       digitalWrite(ledPin, LOW);
       delay(50);
       
       now = rtc.now();//check time again
    }

}
unsigned long range(byte trigPin, byte echoPin, byte vcc)
  {
    digitalWrite(vcc, LOW);
    delay(50);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);    
    unsigned long duration = pulseIn(echoPin, HIGH);
    digitalWrite(vcc, HIGH);
    delay(100);
    return duration * 0.034 / 2;
    
   }
void wakeUp()        // here the interrupt is handled after wakeup
{
}

However, the system is break while loop and then come back to the while loop but not the sleep mode.

I don't understand that collection of words in that order.

You have some serial output that you didn't share.

You have some ideas about the relationship between distance(s), time, logging of data, and sleeping that you haven't shared. Franky, I can't figure out what you are trying to do.

Sorry Paul, I did not mention about it.
My code is about checking whether the object is in certain range by using ultrasonic sensor. If the object is detected, the motor is running. The microsd card module will write the time when that motor runs to microsd. After all that steps, the system should back into sleep mode but I can not make it.

Why does the go-to-sleep stuff only happen between x:00 and x:55? That is the part I don't understand.

It is just only for debugging because I want to run my device at only certain amount of time. So once the motor runs OR after out of time between x:00 and x:55, the device must be in sleep mode.