#include "user.h"
#include "hrtim.h"
#include "adc.h"

static float buf1[2000];
static MovingAverageFilter current_f={.buffer =buf1,.size=2000};

static float buf2[500];
static MovingAverageFilter voltage_f={.buffer =buf2,.size=500};

static uint16_t adc_buffer[2];
static float voltage=0;
static float current=0;

void inventor_init()
{
MAF_Init(&current_f);
MAF_Init(&voltage_f);
	HAL_HRTIM_WaveformCounterStart(&hhrtim1,HRTIM_TIMERID_MASTER);
	HAL_HRTIM_WaveformCounterStart(&hhrtim1,HRTIM_TIMERID_TIMER_A);
	HAL_HRTIM_WaveformCounterStart(&hhrtim1,HRTIM_TIMERID_TIMER_B);

  HAL_ADCEx_Calibration_Start(&hadc1,ADC_SINGLE_ENDED);
  HAL_ADC_Start_DMA(&hadc1,(uint32_t*)adc_buffer,2);
}
void inventor_set(uint16_t frequency,float duty)
{
uint16_t perid = 4608000/frequency;
  uint16_t offset=(uint16_t)(perid*(1.0f-duty)*0.5);
HRTIM1_TIMA->CMP1xR = 50+offset;
HRTIM1_TIMA->CMP2xR = perid*0.5f+50;
HRTIM1_TIMB->CMP1xR = perid*0.5f+50;
  uint16_t cmp2 = 50 - offset;
HRTIM1_TIMB->CMP2xR = cmp2>=0?cmp2:(perid+cmp2);
HRTIM1_TIMA->PERxR = perid;
HRTIM1_TIMB->PERxR = perid;
}
void inventor_start()
{
  HAL_HRTIM_WaveformOutputStart(&hhrtim1, HRTIM_OUTPUT_TA2);
  HAL_HRTIM_WaveformOutputStart(&hhrtim1, HRTIM_OUTPUT_TB2);
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, 1);
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, 1);
}
void inventor_stop()
{
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, 1);
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, 1);
  HAL_HRTIM_WaveformOutputStop(&hhrtim1, HRTIM_OUTPUT_TA2);
  HAL_HRTIM_WaveformOutputStop(&hhrtim1, HRTIM_OUTPUT_TB2);
}
void adc_calculate()
{
  current= MAF_Update(&current_f,(((float)adc_buffer[0]/4096)*3.3-1.65)*10);
    voltage = MAF_Update(&voltage_f, ((float)adc_buffer[1]/4096)*3.3*20.4737-3.75742);
}
inline float current_get()
{
  return current;
}
inline float voltage_get()
{
  return voltage;
}
