polymorphic base structures for easily implementing different gaits. Triangle wave is already in there

Dependents:   robotic_fish_ver_4_9_pixy

fishgait.cpp

Committer:
sandwich
Date:
2014-06-19
Revision:
1:0aa1a6ccf5fe
Parent:
0:aec7653a5b19
Child:
2:d95c40ac8a3e

File content as of revision 1:0aa1a6ccf5fe:

#include "fishgait.h"

fishgait::fishgait()
{
    t=new Timer();
    t->start();
}

fishgait::~fishgait()
{
    t->stop();
    delete t;
}

void fishgait::setTimer(Timer* tObject)
{
    delete t; //not sure if this is safe
    t=NULL;
    t=tObject;
}

triangleGait::triangleGait(float freq, float amplitude) : fishgait(), frq(freq), amp(amplitude)
{
}
/*
triangleGait::~triangleGait()
{
}
*/

float triangleGait::compute()
{
    float halfperiod=(1.0f/(frq/2.0f))*1000; //the half period in ms
    int curtime=t->read_ms(); //read time
    static bool direction=true; //true-> up, false->down
    float out=0;
    if (curtime>halfperiod) {
        direction=!direction;
        t->reset();
    }
    if (direction==true)
        out=float(curtime)/halfperiod;
    else if (direction==false)
        out=1.0f-(float(curtime)/halfperiod);
    out-=0.5; //recenter the wave around 0 instead of 0.5
    out*=amp; //factor in amplitude
    out+=0.5; //recenter around 0.5
    if (out>1)
        out=1;
    else if (out<0)
        out=0;
    return out;
}

squareGait::squareGait(float freq, float amplitude) : fishgait(), frq(freq), amp(amplitude)
{
}
/*
triangleGait::~triangleGait()
{
}
*/

float squareGait::compute()
{
    float halfperiod=(1.0f/(frq/2.0f))*1000; //the half period in ms
    int curtime=t->read_ms(); //read time
    static bool direction=true; //true-> up, false->down
    float out=0;
    if (curtime>halfperiod) {
        direction=!direction;
        t->reset();
    }
    if (direction==true)
        out=1.0f;
    else if (direction==false)
        out=0.0f;
    out*=amp;
    return out;
}