/**** Includes ****/
#include "../utils/utils.h"
#include "mcu/mcu_hal.h"
#include "ain_lpf.h"

using namespace bsp;

/**** Private definitions ****/
/**** Private constants ****/
/**** Private variables ****/
/**** Private function declarations ****/
/**** Public function definitions ****/
bsp::AnalogInLfp::AnalogInLfp(void)
{
	return;
}

bsp::AnalogInLfp::~AnalogInLfp(void)
{
	return;
}

void bsp::AnalogInLfp::init(uint8_t adc_ch)
{
	this->adc_ch = adc_ch;
	this->mul = DEF_AIN_MUL;
	this->div = DEF_AIN_DIV;
	this->offset = DEF_AIN_OFFSET;
	this->strength = 0;
	this->last_read = 0;
	this->last_read_direct = 0;
}

uint16_t bsp::AnalogInLfp::read(void)
{
	//Read ADC
	uint16_t raw = mcu::adc_read(this->adc_ch);
	
	//Convert to mV
	this->last_read_direct = util::convert_muldivoff(raw, this->mul, this->div, this->offset);
	
	// Do filtering
	uint32_t td0 = ((uint32_t)(255 - this->strength) * this->last_read_direct);
	uint32_t td1 = ((uint32_t)(this->strength) * this->last_read);
	uint32_t out = (td0 + td1)/255;
	
	this->last_read = util::sat_cast(out);
	
	return this->last_read;
}

/**** Private function definitions ****/
