#ifndef _ADC_H__
#define _ADC_H__
#include "bsp/bsp.h"
#include "os/os_types.h"

float adc_vref_compesion(void);
float adc_5vref_compesion(void);

/*
inserted ADC 由timer0 ch3触发，
注意：adc所有外部触发都是下降沿触发 
*/
#define ISQ0_OFFSET 0
#define ISQ1_OFFSET 5
#define ISQ2_OFFSET 10
#define ISQ3_OFFSET 15
#define IL_OFFSET   20

#define ADC_REGCHAN_SAMPLE_TIME ADC_SAMPLETIME_239_5
#define ADC_SAMPLE_TIME ADC_SAMPLETIME_28_5
#define ADC_TRIGGER_PHASE ADC12_PREEMPT_TRIG_TMR1CH4

#define PHASE_AB 0
#define PHASE_AC 1
#define PHASE_BC 2


static void __inline adc_phase_current_read(u8 phases, s32 *v1, s32 *v2) {
	*v1 = (s32)((float)((ADC1->pdt2_bit.pdt2 + ADC1->pdt3_bit.pdt3)/2.0f) * adc_5vref_compesion());
	*v2 = (s32)((float)((ADC2->pdt2_bit.pdt2 + ADC2->pdt3_bit.pdt3)/2.0f) * adc_5vref_compesion());
}


static void __inline adc_current_sample_config(u8 phases) {
	//ADC1->psq_bit.psn4 = V_PHASE_I_CHAN;
	//ADC2->psq_bit.psn4 = W_PHASE_I_CHAN;
}

static void __inline adc_disable_ext_trigger(void) {   
	//ADC1->ctrl2_bit.pcten = FALSE;
	//ADC2->ctrl2_bit.pcten = FALSE;
}

static void __inline adc_enable_ext_trigger(void) {	
	//ADC1->ctrl2_bit.pcten = TRUE;
	//ADC2->ctrl2_bit.pcten = TRUE;
}

static __inline__ void adc_clear_irq_flags(void) {
    /* clear the ADC flag */
    adc_flag_clear(ADC1, ADC_PCCE_FLAG);
	adc_flag_clear(ADC2, ADC_PCCE_FLAG);
}


#define adc_update_ext_trigger(trigger) \
	adc_preempt_conversion_trigger_set(ADC1, trigger, TRUE)

void adc_init(void);
void adc_start_convert(void);
void adc_stop_convert(void);
u16 adc_get_vbus(void);
u16 adc_get_acc(void);
u16 adc_get_throttle(void);
void adc_get_uvw_phaseV(u16 *uvw);
u16 adc_get_mos_temp(void);
u16 adc_get_motor_temp(void);
u16 adc_get_ibus(void);
u16 adc_get_vref(void);
void adc_set_vref_calc(float v);
void adc_vref_filter(void);
u16 adc_get_5v_ref(void);
void adc_set_5vref_calc(float v);
u16 adc_get_throttle2(void);
u16 adc_get_thro_5v(void);
u16 adc_get_thro2_5v(void);

#endif /* _ADC_H__ */
