Electronic – way to avoid an infinite loop and reduce CPU power consumption when using PIC and timer0 interrupt

interruptsmicrocontrollerpicprogrammingtimer

I have made a simple program that runs on a P12F629 microcontroller using MikroC.

I need to run some time-critical tasks (e.g. increase internal clock, output data to LED matrix, …).

Instead of a simple loop + Delay_ms() (which has its own set of problems), I use an interrupt:

void main()
{
    InitTimer0();
    while(1);
}

void InitTimer0()
{
   //setup timer0 interrupt
   //...
}

void Interrupt() //will be fired every x ms
{
   //perform some time-critical tasks
   //e.g. increase internal clock
   //...      
}

The problem is a while loop consumes CPU cycles for nothing (and thus reduces battery life).

Is there a way to avoid this?

If I remove the while(1); call at the end of main(), the program runs exactly the same. Does it make a difference? Would adding a Delay_ms(1000) call inside the while loop help in reducing CPU stress?

In x86, I remember there is a halt instruction that halts the CPU until an external interrupt is fired. This would be perfect here. Is there such a thing in MikroC?

Best Answer

If you're driving an LED matrix, I would not think the micro power consumption would be all that significant.

If you put the micro to sleep, the clock stops and you get no interrupt from timer 0 to bring it back. You could use the watchdog timer to bring it back, but it is very variable and the delay may be as much as 25ms.

If you really want to reduce the power consumption and keep time you can run the micro with a 32kHz crystal, which will keep reasonable time and only draws microamps (depending on what else is turned on).

You need to RTFM (datasheet) about the various clock types and modes. There's also a reference manual from Microchip with more information. And then you can figure out how to get your compiler to give the required instructions to the chip.