2018 HongoMechaTech A

Dependencies:   mbed

lib/LinearFunction.cpp

Committer:
Komazawa_sun
Date:
2018-09-18
Revision:
0:e83b840a5f86

File content as of revision 0:e83b840a5f86:

#include "LinearFunction.h"

LinearFunction::LinearFunction(unsigned int op_period_ms):
    _op_period(((op_period_ms > 0) ?(op_period_ms < LF_MAX_TIME) ?op_period_ms :LF_MAX_TIME :1) / 1000.0)
{
    _ticker.attach(this, &LinearFunction::_on_operate, _op_period);    
}

void LinearFunction::set(const double val, const double intercept, const unsigned int ct_ms)
{
    
    if(_range !=  val - intercept){
        reset();
        _range = val - intercept;
    }
    
    _intercept = intercept;
    
    _timer.start();    
    _ct_s = ((ct_ms > 0) ?(ct_ms > _op_period * LF_MAX_TIME) ?ct_ms :_op_period * LF_MAX_TIME :1) / 1000.0;    
}

void LinearFunction::reset()
{
    _ct_s = 0;
    _range = 0;
    _intercept = 0;
    _current_val = 0;
    _timer.reset();
    _timer.stop();
}

double LinearFunction::get_val()
{
    return _current_val + _intercept;
}

void LinearFunction::_on_operate()
{
    
    if(_ct_s <= _timer.read_ms() / 1000.0){
        _current_val = _range;
        _timer.stop();
        if(_current_val != _range)
            _timer.reset();
    }else{
        _current_val = (_range / _ct_s) * (_timer.read_ms() / 1000.0);
    }
    
}