#include <stdio.h>

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

extern ADC_HandleTypeDef ADC_HANDLER_SBC;

void adc_demo()
{
    // while(1) {
    CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
    DWT->CYCCNT = 0;
    DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
    HAL_GPIO_WritePin(GPIOF, GPIO_PIN_11, GPIO_PIN_SET);
    // HAL_Delay(2);
    // }
    while(1) {
        int eps_on = HAL_GPIO_ReadPin(GPIOF, GPIO_PIN_10);
        int volt = measure_voltage(ADC_HANDLER_SBC, EPS_CAP_ID_SBC);

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

        // int vdda_milli_volt = (VREFINT_CAL_VREF * (*VREFINT_CAL_ADDR)) / val;
        // int volt = vdda_milli_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(4);
    }
}