RTC Calibration Sample

Dependencies:   mbed

Revision:
0:897d43c0dcf0
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Tue Aug 21 02:37:37 2018 +0000
@@ -0,0 +1,62 @@
+#include "mbed.h"
+
+Serial pc(USBTX, USBRX);
+DigitalOut myled(LED1);
+
+void resetClockTickCounter () {
+    LPC_RTC->CCR |= (1<<1); // CTC Reset
+    LPC_RTC->CCR &= ~(1<<1);
+}
+
+void calibConfig (int value, int dir) {
+    if (dir) {
+        LPC_RTC->CALIBRATION = (value & 0x1ffff) | ((dir == -1) ? (1<<17) : 0);
+        LPC_RTC->CCR &= ~(1<<4); // Calibration counter disable.
+    } else {
+        LPC_RTC->CALIBRATION = 0;
+        LPC_RTC->CCR |= (1<<4); // Calibration counter disable.
+    }
+}
+extern "C"
+void RTC_IRQHandler () {
+    time_t sec = time(NULL);
+    struct tm *t = localtime(&sec);
+
+    myled = !myled;
+    pc.printf("%d  %04d-%02d-%02d %02d:%02d:%02d\r\n", sec,
+        t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
+    LPC_RTC->ILR |= (1<<0);
+}
+
+int main() {
+
+    pc.baud(115200);
+    pc.printf("RTC Calibration\r\n");
+    set_time(1514732400); // 2018-01-01 00:00:00
+    LPC_RTC->CIIR |= (1<<0);
+    NVIC_EnableIRQ(RTC_IRQn);
+
+    for (;;) {
+        if (pc.readable()) {
+            char c = pc.getc();
+            switch (c) {
+            case '0':
+                calibConfig(0, 0);
+                pc.printf("0\r\n");
+                break;
+            case 'f': // Forward
+                calibConfig(4, 1);
+                pc.printf("F\r\n");
+                break;
+            case 'b': // Backward
+                calibConfig(4, -1);
+                pc.printf("B\r\n");
+                break;
+            case 'r': // Reset
+                resetClockTickCounter();
+                pc.printf("R\r\n");
+                break;
+            }
+        }
+    }
+}