Search code examples
cmicrocontrollermicrochipatmel

How to call an event after x minutes while still running?


I'm quite new in programming, so please bear with me.

I'm working with a microcontroller, therefore I'm using Microchip Studio.

My code is simplified build up like this:

While(1){
 if(ErrorFlag==1)
   timer_restart++;
 else
   timer_restart=0;
 if (time_restart == 600000)
   restart()
//Remaining code
} // EndWhile

My problem is that I would like to call restart() after around 5 minutes. Right now I have no clue how long it takes. Is there a better way to implement that?

I've tried to find out what time one-WhileLoop-Rotation requires with the clock() function. But I'm getting a ErrorMessage "undefined reference". I think that Microchip Studio does not know those functions.

I maybe could use something like:

while(1){
 while(ErrorFlag==1){
  delay_ms(5000);
  restart();
  ErrorFlag=0;
}}

But then the rest of the code is interrupted. Is there any advice someone can give me?


Solution

  • "Busy-while" or "busy-delay" are rarely ever the correct solution. Apart from being inaccurate, they also lock up your CPU at 100% and consuming current needlessly.

    You need to use the actual on-chip hardware peripheral timers, either by polling a timer flag on regular basis or by using interrupts. As for how to do that, it depends on the specific MCU.