Class which provides a handy interface to refresh a loop with microsecond precision within an RTOS.

Revision:
0:fb0d810af3de
Child:
1:4b00feda7702
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FixedRefresh.cpp	Tue Aug 02 01:41:36 2016 +0000
@@ -0,0 +1,48 @@
+/*
+ * FixedRefresh.cpp
+ *
+ *  Created on: Jun 26, 2016
+ *      Author: Developer
+ */
+
+#include <FixedRefresh.hpp>
+
+
+
+FixedRefresh::FixedRefresh()
+:waitSemaphore(0) {
+    // Start the timer that measures the time between successive calls.
+    elapsedTime.start();
+}
+
+FixedRefresh::~FixedRefresh() {
+    // TODO Auto-generated destructor stub
+}
+
+/* More complicated, Thread does not have a wait_us function, necessitating the use of
+ * a semaphore and a callback function to perform the wait operation.
+ */
+
+bool FixedRefresh::refresh_us(uint32_t micros) {
+    /* Capture the elapsed time. */
+    uint32_t elapsedTimeCapture = elapsedTime.read_us() + 7;
+    // If the elapsed time is less than the set time, then we can wait.
+    if(elapsedTimeCapture < micros) {
+        uint32_t waitTime = micros - elapsedTimeCapture;
+        // Activate the timer callback.
+        waitTimer.attach_us(this, &FixedRefresh::timerCallback, waitTime);
+        // Call the wait function again. Since we have called wait before, it is locked.
+        // This time, we actually wait for the timerCallback function to release it.
+        waitSemaphore.wait();
+        return true;
+    }
+    else {
+        return false;
+    }
+}
+
+void FixedRefresh::timerCallback() {
+    elapsedTime.reset();
+    waitSemaphore.release();
+}
+