Using delays in a software code is usual to embedded programmers. A normal delay function might be used to create a period of no operation through a for loop iterating for a few 1000 cycles. But these types of delays need not be accurate and fundamentally, it is not a good programming practice. So, TIMER/COUNTER is a software designed to count the time interval between events. It counts the cycle of the peripheral clock or an externally-supplied clock.
#define Power_Control_Reg LPC_SC->PCONP #define Match_Control_Reg LPC_TIM0->MCR #define Peripheral_Clk0 LPC_SC->PCLKSEL0 #define Peripheral_Clk1 LPC_SC->PCLKSEL1 #define Prescalar_Reg LPC_TIM0->PR #define Timer0_Match_Reg LPC_TIM0->MR0 #define Timer0_Timer_Counter LPC_TIM0->TCR #define Interrupt_Reg LPC_TIM0->IR #define MatchReg0_Int 0 #define MatchReg0_Rst 1 #define Timer0_Power 1 #define Timer1_Power 2 #define Timer2_Power 22 #define Timer3_Power 23 #define Timer0_Peripheral 2 #define Timer1_Peripheral 4 #define Timer2_Peripheral 12 #define Timer3_Peripheral 14 #define Timer_Counter_Enable 0 #define BlinkDir LPC_GPIO2->FIODIR #define BlinkPin LPC_GPIO2->FIOPIN #define Led 0
Power_Control_Reg |= (1<<Timer0_Power); Match_Control_Reg = (1<<MatchReg0_Int) | (1<<MatchReg0_Rst);
PreScale = pclk/ReqCntsPerSec; Prescalar_Reg = PreScale - 1;
Match_Control_Reg = (1<<MatchReg0_Int) | (1<<MatchReg0_Rst); Timer0_Match_Reg = 1000000; // 1 sec delay
void TIMER0_IRQHandler(void) { uint8_t interrupt_bit; interrupt_bit = Interrupt_Reg; // When MR0 match occurs, flag is set. Bit 0 of T0 interrupt reg Interrupt_Reg = interrupt_bit; // Writing logic 1 clears the flag BlinkPin ^= (1<<Led); // Toggle the LED }
The same logic can be applied to generate different types of delays based on your particular application. Creating a delay that is calculated based on the peripheral clocks is always a good coding practice. The sample code for this tutorial is available in the Code Library under the section ARM.