/* Includes ------------------------------------------------------------------*/
#include "FE82160.h"
#include "bsp_uart1.h"
#include <stdio.h>

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
uint8_t complete_flag = 0;
uint32_t Adc_Value = 0;
/* Private function prototypes -----------------------------------------------*/
void MY_ADC_Init(void);
/* Private functions ---------------------------------------------------------*/

int main(void)
{
  SystemCoreClockUpdate();
  uart1_init(24000000, 115200);
  MY_ADC_Init();

  /* Infinite loop */
  while (1)
  {
    if (complete_flag == 1)
    {
      complete_flag = 0;
      printf("VCAP is %d\r\n", Adc_Value);
    }
  }
}

/**
  * @brief  ADC Configuration(Channel7, single mode, no auto acceleration, 
  *         64 clock division, software start, sample time: 8 cycles)
  * @note   Channel_7 conversion value is VCAP
  * @retval None
  */
void MY_ADC_Init(void)
{
  ADC_InitTypeDef ADC_InitStruct = {0};

  RCC_APBPeriphClockCmd(RCC_APBPeriph_ADC, ENABLE);

  ADC_InitStruct.ADC_SamplingTime = ADC_SAMPLE_8CYCLE;
  ADC_InitStruct.ADC_SingleChannelSel = ADC_SINGLE_CHANNEL_7;
  ADC_InitStruct.ADC_SingleContinueMode = ADC_MODE_SINGLE;
  ADC_InitStruct.ADC_ClkSel = ADC_CLOCK_PCLK_DIV64;
  ADC_InitStruct.ADC_CircleMode = ADC_MULTICHANNEL_NONCIRCLE;
  ADC_InitStruct.ADC_AutoAccumulation = ADC_AUTOACC_DISABLE;
  ADC_InitStruct.ADC_ExternalTrigConv1 = ADC_SOFTWARE_START;
  ADC_InitStruct.ADC_ExternalTrigConv2 = ADC_SOFTWARE_START;
  ADC_Init(&ADC_InitStruct);

  ADC_Cmd(ENABLE);
  ADC_ITConfig(ADC_IT_CHANNEL7, ENABLE);
  NVIC_SetPriority(ADC_IRQn, 1);
  NVIC_EnableIRQ(ADC_IRQn);

  ADC_SoftwareStartConvCmd(ENABLE);
}

/**
  * @brief This function handles ADC Interrupt.
  */
void ADC_IRQHandler(void)
{
  if ((ADC_GetFlagStatus(ADC_IT_CHANNEL7)) != RESET)
  {
    complete_flag = 1;
    Adc_Value = ADC_GetConversionValue(ADC_SINGLE_CHANNEL_7);
    ADC_ClearFlag(ADC_IT_CHANNEL7);
  }
}

#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif
