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

FixedRefresh.cpp

Committer:
Electrotiger
Date:
2016-08-02
Revision:
1:4b00feda7702
Parent:
0:fb0d810af3de

File content as of revision 1:4b00feda7702:

/*
 * FixedRefresh.cpp
 *
 *  Created on: Jun 26, 2016
 *      Author: Developer
 */

#include <FixedRefresh.h>



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();
}