Andrew Boyson / clock

Dependents:   oldheating gps motorhome heating

timer.c

Committer:
andrewboyson
Date:
2018-01-25
Revision:
26:0421132e6eaf
Parent:
25:81014a201736
Child:
29:9332cf906aad

File content as of revision 26:0421132e6eaf:

#include <stdint.h>
#include <stdbool.h>

#include "peripherals.h"
#include "timer.h"

uint32_t TimerNowCount()
{
    return LPC_TIM0->TC;
}
uint32_t TimerIntervalCount(uint32_t* pLastCount)
{
    uint32_t thisCount = LPC_TIM0->TC;
    uint32_t period = thisCount - *pLastCount;    
    *pLastCount = thisCount;
    return period;
}
uint32_t TimerSinceCount(uint32_t startCount)
{
    return LPC_TIM0->TC - startCount; 
}
uint32_t TimerSinceMs(uint32_t startCount)
{
    uint32_t count = LPC_TIM0->TC - startCount;
    return count / TIMER_COUNT_PER_MS;
}

static uint32_t secondsBaseCount = 0;

uint32_t TimerCountSinceLastSecond()
{
    return LPC_TIM0->TC - secondsBaseCount; 
}
int32_t TimerMultiplyFractionalPart(int32_t value, uint32_t timerCountSinceLastSecond)
{
    int64_t fraction;
    
    fraction = timerCountSinceLastSecond;
    fraction <<= 32;
    fraction /= TIMER_COUNT_PER_SECOND;
              
    return (value * fraction) >> 32;
}

bool TimerTicked = false;

void TimerMain()
{
    TimerTicked = TimerCountSinceLastSecond() > TIMER_COUNT_PER_SECOND;
    
    if (TimerTicked) secondsBaseCount += TIMER_COUNT_PER_SECOND;
}
void TimerInit()
{    
    LPC_TIM0->TCR     =     2; // 21.6.2 Timer Control Register - Reset TC and PC.
    LPC_TIM0->CTCR    =     0; // 21.6.3 Count Control Register - Timer mode
    LPC_TIM0->PR      =     0; // 21.6.5 Prescale register      - Don't prescale 96MHz clock (divide by PR+1).
    LPC_TIM0->MCR     =     0; // 21.6.8 Match Control Register - no interrupt or reset
    LPC_TIM0->TCR     =     1; // 21.6.2 Timer Control Register - Enable TC and PC
}