Andrew Boyson / clock

Dependents:   oldheating gps motorhome heating

Revision:
26:0421132e6eaf
Parent:
25:81014a201736
Child:
29:9332cf906aad
--- a/timer.c	Mon Jan 22 18:54:23 2018 +0000
+++ b/timer.c	Thu Jan 25 07:54:54 2018 +0000
@@ -1,27 +1,20 @@
 #include <stdint.h>
+#include <stdbool.h>
 
 #include "peripherals.h"
 #include "timer.h"
 
-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
+uint32_t TimerNowCount()
+{
+    return LPC_TIM0->TC;
 }
-uint32_t TimerPeriodCount(uint32_t* pLastCount)
+uint32_t TimerIntervalCount(uint32_t* pLastCount)
 {
     uint32_t thisCount = LPC_TIM0->TC;
     uint32_t period = thisCount - *pLastCount;    
     *pLastCount = thisCount;
     return period;
 }
-uint32_t TimerNowCount()
-{
-    return LPC_TIM0->TC;
-}
 uint32_t TimerSinceCount(uint32_t startCount)
 {
     return LPC_TIM0->TC - startCount; 
@@ -31,3 +24,37 @@
     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
+}