Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Timer.cpp
- Committer:
- elevatorguy
- Date:
- 2012-12-30
- Revision:
- 2:e26c096f1946
- Child:
- 3:88da6c0412b0
File content as of revision 2:e26c096f1946:
#include "Timer.h"
//This class uses Timer 1
// static data initialization (only called once)
bool Timer::timer1initialized = false;
int Timer::resolution = 1000000;
void Timer::initTimer1(int res) //microseconds accuracy
{
uint8_t pclk;
uint32_t pclkdiv = (LPC_SC->PCLKSEL0 >> 4) & 0x03; //PCLK for Timer 1 (page 56)
switch ( pclkdiv ) // table 42 (page 57 in user manual)
{
case 0x00:
default:
pclk = 4;
break;
case 0x01:
pclk = 1;
break;
case 0x02:
pclk = 2;
break;
case 0x03:
pclk = 8;
break;
}
LPC_TIM1->TCR = 0x02; /* reset timer */
LPC_TIM1->PR = (SystemCoreClock / (pclk * res)); //default: microsecond steps
LPC_TIM1->MR0 = 2147483647; /* highest number a 32bit signed int can store (for us ~ 35.79 minutes, or, for ms ~ 596.52 hours ) */
LPC_TIM1->IR = 0xff; /* reset all interrrupts */
LPC_TIM1->MCR = 0x02; /* reset timer on match */
LPC_TIM1->TCR = 0x01; /* start timer */
/* The timer simply goes on forever! It just resets itself when it hits the max number for TC */
timer1initialized = true;
resolution = res;
}
Timer::Timer()
{
if(!timer1initialized)
{
initTimer1(resolution); //default resolution
}
starttime = 0;
stoptime = 0;
running = false;
}
//for when we want to allow lower counting resolution, eg. milliseconds
//so we can count longer than the 35 minutes with microsecond resolution
Timer::Timer(int res) // millisecond, res = 1000
{
if(!timer1initialized)
{
initTimer1(res); //custom resolution
}
starttime = 0;
stoptime = 0;
running = false;
}
void Timer::start()
{
starttime = LPC_TIM1->TC;
stoptime = 0; //clear previous stoptime
running = true;
}
void Timer::stop()
{
stoptime = LPC_TIM1->TC;
running = false;
}
void Timer::reset()
{
if(running)
{
starttime = LPC_TIM1->TC;
}
else
{
starttime = 0;
}
stoptime = 0;
}
float Timer::read()
{
if(running)
{
int currenttime = LPC_TIM1->TC;
return (currenttime - starttime) / (resolution*1.0);
}
else // compare startime and stoptime
{
return (stoptime - starttime) / (resolution*1.0);
}
}
Timer::operator float()
{
return read();
}