Drivers for the mini robot designed for Princeton's MAE 433 course.

Dependencies:   mbed-dsp mbed-rtos mbed

Dependents:   MAE433_Library_Tester RobotBalancerv2

FixedRefresh.cpp

Committer:
Electrotiger
Date:
2016-06-29
Revision:
6:076fcae78bac
Child:
7:28f3a76792cd

File content as of revision 6:076fcae78bac:

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

#include <FixedRefresh.hpp>



FixedRefresh::FixedRefresh()
:waitSemaphore(1) {
    // 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() + 12;
    // If the elapsed time is less than the set time, then we can wait.
    if(elapsedTimeCapture < micros) {
        uint32_t waitTime = micros - elapsedTimeCapture;
        // Call the semaphore's wait function, thereby locking it.
        waitSemaphore.wait();
        // 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();
    waitSemaphore.release();
}