Sunday, January 8, 2012

Frequency counter using LPC17xx

I got a couple of requests for the tutorial of making a frequency counter using LPC17xx. So I am providing the code and explanation of making a frequency counter in this post.

The basic idea of making a frequency counter is to count the number of cycles of the input in one second. We can keep one counter that keeps counting the rising/falling edges of the input signal. Then we can read the value of this counter once in a second and then clear it. The value we read from the counter is nothin but the frequency of the input signal.

1. Initialization of the counter

LPC_SC->PCONP |= 1 << 2; //Power up TimerCounter1

LPC_TIM1->TCR |= 1 << 0; // Counter mode
LPC_TIM1->CTCR |= 2; // Count on falling edges
LPC_TIM1->CTCR |= 1 << 2; // CAP1.1 is the input pin for which the input signal needs to be connected.


LPC_PINCON->PINSEL3 |= 3 << 6; // Make P1.19 as CAP1.1

 LPC_TIM1->TCR |= 1 << 1; // Reset the counter
LPC_TIM1->TCR |= 1 << 0; // Start counter



2. Initialization of the timer which generates interrupt once in a second
LPC_SC->PCONP |= 1 << 1; //Power up Timer0
LPC_SC->PCLKSEL0 |= 3 << 2; // Clock for timer = CCLK/8

LPC_TIM0->MR0 = 12499999; // Assuming that clk freq = 100 MHz, this value is calculated to generate an interrupt once in a second.


LPC_TIM0->MCR |= 1 << 0; // Interrupt on Match0 compare
LPC_TIM0->TCR |= 1 << 1; // Reset Timer0

NVIC_EnableIRQ(TIMER0_IRQn); // Enable timer interrupt

LPC_TIM0->TCR |= 1 << 0; // Start timer



3. Timer interrupt routine

In this routine we need to read the value of the counter if the interrupt was generated by MR0 and then we need to clear the counter.

inputFreq = LPC_TIM1->TC; // Read the counter value
LPC_TIM1->TCR |= 1 << 1; // Reset the counter




The input frequency value is now stored in the variable inputFreq. The main.cpp file for this program can be found here.

WARNING: This code needs to be integrated with the CMSIS LPC17xx code base and needs to be compiled. I have not tested this code on hardware.

4 comments:

vairamani said...

i have modified your code for IAR really your code helped me in making a counter to count pulses for one second.


k.vairamani

vairamani said...

i have modified your code for IAR really your code helped me in making a counter to count pulses for one second.


k.vairamani

lotus said...

Thank you so much. it is very useful for my school project

Unknown said...

thw main,cpp file is not found in that site. Please upload it