Logging data for specific time period according to measurement value


I can't figure out how to program this part of code:

My setup consists of an Arduino mega, temperature sensor, RTC and sd card slot. I have RTC, SD card, and temperature sensors all working just fine, but now can't figure out how to program it so it logs data automatically for a specific time period(let's say 30 minutes) after the temperature reaches specified value? It has to check the same temperature condition after that time period and if it no longer meets requirements it stops the data logging process, and if does meet this condition it records data for 30 more minutes.

I think this should be quite simple, but as a beginner with this being my first Arduino project and no experience in programming I am really struggling here.

Any help or tips will be highly appreciated.

You should study the tutorials for Blink Without Delay and simulated multitasking, here and here, all of which involve doing more than one thing at a time, and pose timing challenges.

Check this library:


It's very easy to setup timers. Set a flag that only change back after the timer is up. Don't forget to stop setting up the timer when temp reaches your limit by using another flag that keep track if the timer have been setup. If it is setup then log.

Hope this help.

Also read this post very well if you want to understand more about how to correctly setup your own code:


What I often do when faced with a similar problem is to write some comments and call a non-existent function.

float tempF = getTemperature(); // I assume that you have some function to get the temperature
if(tempF > tooHot) // Damn, it's hot in here

Then, I think about HOW I would write that function.

The millis() function is usually used as a replacement for delay(), but it can be used to create code that blocks for a while, too.

void logTheTemperatureForThirtyMinutes()
   unsigned long startedLogging = millis();

   // Open the file where logging is to happen

   while(millis() - startedLogging <= thirtyMinutesInMilliseconds)
      // Read and log the temperature

   // Close the file

Add some code to do what the comments say, and some global or static variables with reasonable values, and you’re done.