Mark Gottscho / HardwareTimersLib

Fork of HardwareTimersLib by Mark Gottscho

Revision:
1:7dde0e4d30da
Child:
2:5056ec8c52e8
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Timer_TPM.cpp	Sun Mar 09 01:09:56 2014 +0000
@@ -0,0 +1,59 @@
+/* Timer_TPM.cpp
+ * Tested with mbed board: FRDM-KL46Z
+ * Author: Mark Gottscho
+ * mgottscho@ucla.edu
+ */
+
+#include "mbed.h"
+#include "HardwareTimer.h"
+#include "Timer_TPM.h"
+
+//Init class static variable
+bool Timer_TPM::__initialized_tpm = false;
+uint16_t Timer_TPM::__rolloverValue = 0xFFFF;
+uint32_t Timer_TPM::__count = 0;
+
+
+Timer_TPM::Timer_TPM() :
+        HardwareTimer(20.8333333333) //20.833... ns per tick, roll over at maximum possible value to reduce interrupt frequency
+        {   
+}
+
+Timer_TPM::~Timer_TPM() {}
+
+void Timer_TPM::disableTimer() {
+    if (!__valid)
+        return;
+        
+    TPM0->SC = 0; //Reset TPM
+    __enabled = false;
+}
+
+uint32_t Timer_TPM::getTick() {
+    if (!__valid)
+        return 0;
+        
+    //Get raw time
+    __disable_irq();
+    TPM0->CNT = 0; //Need to write to the TPM CNT register in order to read it (buffering)
+    uint16_t tick = TPM0->CNT;
+    uint32_t count = __count;
+    __enable_irq();
+    
+    //Convert to ticks
+    return (uint32_t) count * __rolloverValue + tick;
+}
+
+void Timer_TPM::__set_tpm(uint16_t count) {
+    //TPM0->SC &= ~TPM_SC_CMOD_MASK; //Stop clock
+    TPM0->CNT = 0; //Set the count register
+    TPM0->MOD = count; //Set the modulo register
+    TPM0->SC |= TPM_SC_TOIE_MASK; //Enable interrupt
+    TPM0->SC |= TPM_SC_CMOD(1); //Start the timer. Timer will increment on the TPM clock edges, not an external clock
+}
+
+void Timer_TPM::__isr_tpm() {
+    TPM0->SC |= TPM_SC_TOF_MASK;
+    __set_tpm(__rolloverValue);
+    __count++;
+}
\ No newline at end of file