TMR0 – IRQ

This example modifies TMR0 in the IRQ to obtain a roll over every 1mS. You could use a timer with a prescaller for this, but in this example we show how it’s possible on TMR0 with no prescaller (leaving your prescaller timers available for other uses)

Using your own irq function
#include "mcc_generated_files/timer/tmr0.h"

	//----- SET ADDRESS OF OUR INTERRUPT HANDLERS -----
	Timer0_OverflowCallbackRegister(Our_TMR0_InterruptHandler);

	Timer0_Start();


//Inline assembler access bank variables
__near static unsigned char uc_asm_irq_temp;		// near qualifier specifies access RAM
__near static unsigned char uc_asm_irq_temp1;

//***********************************************
//***********************************************
//********** TIMER 0 INTERRUPT HANDLER **********
//***********************************************
//***********************************************
void Our_TMR0_InterruptHandler(void)
{
	//(Timer 0 - Heartbeat every 1mS)
	
	//Modify TMR0 value so we roll over every 1mS
	asm("GLOBAL _uc_asm_irq_temp");
	asm("GLOBAL _uc_asm_irq_temp1");
	//Reset timer for next rollover
	asm("movff	TMR0L,_uc_asm_irq_temp");		//read_current_timer_value (read low byte loads high byte)
	asm("movff	TMR0H,_uc_asm_irq_temp1");
	asm("movlw	0x6b");
	asm("addwf	_uc_asm_irq_temp,f,c");			//(1 = file register, 0 = access ram)
	asm("movlw	0xf0");
	asm("addwfc	_uc_asm_irq_temp1,f,c");		//(1 = file register, 0 = access ram)
	asm("movff	_uc_asm_irq_temp1,TMR0H");		//Store new value (high byte first)
	asm("movff	_uc_asm_irq_temp,TMR0L");

	//This code takes 10 instruction cycles
	//The timer is inhibited for 2 instruction cycles after the low byte is written
	//Therefore subtract 12 from the value to be written
	//For 4MHz clock 1mS irq = 1000 cycles.  Minus 12 = 988.  0xFFFF - 988 = 0xFC23
	//For 4MHz clock 10mS irq = 10000 cycles.  Minus 12 = 988.  0xFFFF - 988 = 0xd8fb
	//For 16MHz clock 1mS irq = 4000 cycles.  Minus 12 = 3988.  0xFFFF - 3988 = 0xF06B
	//For 16MHz clock 10mS irq = 40000 cycles.  Minus 12 = 39988.  0xFFFF - 39988 = 0x63CB
	//For 32MHz clock 1mS irq = 8000 cycles.  Minus 12 = 7988.  0xFFFF - 7988 = 0xE0CB
	//For 40MHz clock 10mS irq = 50000 cycles (1:2).  Minus 12 = 49988.  0xFFFF - 49988 = 0x3cbb
	//For 40MHz clock 1mS irq = 10000 cycles.  Minus 12 = 9988.  0xFFFF - 9988 = 0xd8fb

}
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *