#include <stdio.h>

#include "cmsis_os.h"
#include "ImC/imc_api.h"
#include "stm32l5xx_hal.h"

extern ADC_HandleTypeDef ADC_HANDLER_SBC;

void vrefint_expr() {
    LL_ADC_EnableInternalRegulator(ADC1);
    HAL_ADCEx_Calibration_Start(&hadc1, ADC_SINGLE_ENDED);
    int vref_enabled = ADC_VREFINT_INSTANCE(&hadc1);
    printf("vref enabled: %d\r\n", vref_enabled);
    while(1) {
        continue;
        // int eps_on = HAL_GPIO_ReadPin(GPIOF, GPIO_PIN_10);
        // int volt = measure_voltage(ADC_HANDLER_SBC, EPS_CAP_ID_SBC);

        HAL_ADC_Start(&hadc1);
        // Poll ADC Peripheral & TimeOut = 1mSec
        while(HAL_ADC_PollForConversion(&hadc1, 1000) != HAL_OK);
        int val = HAL_ADC_GetValue(&hadc1);
        // HAL_ADC_Stop(&ADC_HANDLER_SBC);


        // int vdda_milli_volt = (VREFINT_CAL_VREF * (*VREFINT_CAL_ADDR)) / val;
        // int volt = vdda_milli_volt;
        int volt = val * 0.61274014;

        printf("ADC val: %d, volt: %d\r\n", val, volt);

        // uint32_t tick = HAL_GetTick();
        // uint32_t tick = DWT->CYCCNT;
        // HAL_ADC_Start(&ADC_HANDLER_SBC);
        // HAL_ADC_PollForConversion(&ADC_HANDLER_SBC, HAL_MAX_DELAY);
        // int volt = HAL_ADC_GetValue(&ADC_HANDLER_SBC);
        // printf("capacitor voltage: %d\r\n", volt);
        // HAL_ADC_Stop(&ADC_HANDLER_SBC);
        // printf("capacitor voltage: %d.%03d\r\n", volt/1000, volt%1000);
        // printf("%d %d %d.%03d\r\n", tick, eps_on, volt/1000, volt%1000);
        osDelay(50);
    }
}