Use of two timers to implement a counter of an external signal
Timer2.cpp
- Committer:
- garyr
- Date:
- 2014-01-28
- Revision:
- 0:e619b6823668
File content as of revision 0:e619b6823668:
/*
This counter establishes the measurent interval.
MAT2.0 (P8) is set when the interval has elapsed.
This code generates timed intervals T = <prescale> * 100 ms.
mbed pin 8 goes high at the beginning of the interval and returns to zero at the end.
The interrupt occurs at the end of the interval.
*/
#include "TARGET_LPC1768/LPC17xx.h"
#include "mbed.h"
#include "Timer2.h"
funcptr timer2ISR;
void Timer2_IRQHandler(void)
{
if (LPC_TIM2->IR & 1) // MR0 interrupt
{
LPC_TIM2->IR = 1; // clear the interrupt
if (timer2ISR)
timer2ISR();
}
}
void Timer2_init(funcptr callback)
{
timer2ISR = callback;
LPC_SC->PCONP |= (1<<22); // Power on the Timer2
LPC_SC->PCLKSEL1 &= ~(3<<12);
LPC_SC->PCLKSEL1 |= (1<<12); // Select CCLK for Timer2
LPC_PINCON->PINSEL0 &=~(3<<12);
LPC_PINCON->PINSEL0 |= (3<<12); // Connect MAT2.0 to mbed P8
LPC_PINCON->PINMODE0 &=~(3<<12);
LPC_PINCON->PINMODE0 |= (2<<12); // no pull-p or pull-down
if (callback)
{
NVIC_SetPriority(TIMER2_IRQn, 10);
NVIC_SetVector(TIMER2_IRQn, (uint32_t)&Timer2_IRQHandler);
NVIC_EnableIRQ(TIMER2_IRQn);
}
}
void Timer2_start(int prescale)
{
LPC_TIM2->TCR = 2; // Reset the timer and prescale counters on next PCLK
LPC_TIM2->MR0 = CLOCK/10; // Set the Timer2 match register for 100 ms resolution
LPC_TIM2->CTCR = 0; // Timer2 is incremented when the prescale register == 0
LPC_TIM2->PR = prescale; // Update prescale register
LPC_TIM2->MCR = 3; // Interrupt on MR0 and reset
LPC_TIM2->EMR = (3<<4)|1; // Toggle MAT2.0 when match occurs.
LPC_TIM2->TCR = 1; // Enable Timer2
LPC_TIM3->TCR = 1; // Enable Timer3
}