#include "vbus_sensor.h"
#include "bsp/bsp.h"

static vbus_t _vbus;
void vbus_sensor_init(void){
	_vbus.voltage_avg = 0;
	_vbus.avg_count = 5;
	HAL_ADC1_ChanConfig(VBUS_SENSOR_ADC_CHANNEL);
	vbus_sample_voltage();
}

void vbus_sample_voltage(void){
	u32 vadc = 0;
	u32 max = 0, min = 0xFFFFFFF;
	for (int i = 0; i < _vbus.avg_count; i++) {
		u32 one = HAL_ADC1_ReadValue(VBUS_SENSOR_ADC_CHANNEL);
		vadc += one;
		if (min > one) {
			min = one;
		}
		if (max < one) {
			max = one;
		}
	}
	vadc -= (max + min);
	vadc = vadc / (_vbus.avg_count - 2);
	_vbus.voltage_avg = ((float)vadc)/(65536.0f) * ADC_REFERENCE_VOLTAGE / VBUS_PARTITIONING_FACTOR;
}


float vbus_get_voltage(void){

	return _vbus.voltage_avg;
}

