I want to set a timer to count milliseconds without interrupt.
So I configure a timer (CPU frequency = 120 Mhz)
void SysTimerInit(void) { Uint32 prescaler; // Make sure timers are stopped: CpuTimer1Regs.TCR.bit.TSS = 1; // Initialize timer period to maximum: CpuTimer1Regs.PRD.all = 0xFFFFFFFF; prescaler = 120000-1; //1000us->1ms CpuTimer1Regs.TPR.bit.TDDR = (prescaler & 0x0000FFFF); CpuTimer1Regs.TPRH.bit.TDDRH = (prescaler >> 8); // Initialize timer control register: CpuTimer1Regs.TCR.bit.TRB = 1; // 1 = reload timer CpuTimer1Regs.TCR.bit.SOFT = 1; CpuTimer1Regs.TCR.bit.FREE = 1; // Timer Free Run CpuTimer1Regs.TCR.bit.TIE = 0; // 0 = Disable/ 1 = Enable Timer Interrupt CpuTimer1Regs.TCR.bit.TSS = 0; // 1 = Stop timer, 0 = Start/Restart Timer }
And functions to handle the counter
void SysTimerSet(Uint32 *compare_val, Uint32 count_ms) { Uint32 timer_count_val = CpuTimer1Regs.TIM.all; *compare_val = timer_count_val - count_ms; } Uint16 SysTimerElapsed(Uint32 *compare_val) { Uint32 timer_count_val = CpuTimer1Regs.TIM.all; return (timer_count_val <= *compare_val); }
And I test.
SysTimerInit(); SysTimerSet(&compare_val, 100); while(1) { if(SysTimerElapsed(&compare_val)) { SysTimerSet(&compare_val, 100); } }
In the debugger I should see variable compare_val decremented by 100. But I see some random numbers. Where is my mistake?