/**
  ******************************************************************************
  * @file    main.c
  * @author  MCU Application Team
  * @brief   Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2023 Puya Semiconductor Co.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by Puya under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "ms32c0xx.h"

/* Private define ------------------------------------------------------------*/
#define HSI_TIMEOUT_VALUE          ((uint32_t)100)  /* 100 ms */
#define CLOCKSWITCH_TIMEOUT_VALUE  ((uint32_t)5000) /* 5 s    */

#define ERROR_HSI_TIMEOUT          0x01
#define ERROR_CLKSWITCH_TIMEOUT    0x02

/* Private variables ---------------------------------------------------------*/
static __IO uint32_t Tick;
volatile uint16_t error = 0; 
uint32_t ADC_Value;

/* Private user code ---------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static __INLINE void APP_SystemClockConfig(void);
static __INLINE void APP_Delay(int32_t Delay);
static __INLINE void APP_ADCCalibrate(void);
static __INLINE void APP_ADCConfig(void);

/**
  * @brief  Main program.
  * @param  None
  * @retval int
  */
int main(void)
{
  SysTick_Config(8000); /* 1ms config */
  APP_SystemClockConfig();

  if (error != 0)
  {
    while(1) /* endless loop */
    {
    }
  }

  RCC->APBENR1 |= (RCC_APBENR1_PWREN);  
  RCC->APBENR2 |= (RCC_APBENR2_SYSCFGEN);  

  RCC->APBENR2 |= (RCC_APBENR2_ADCEN);             /* Enable ADC Clock */
  RCC->APBENR2 |= (RCC_APBENR2_VREFBUFEN);         /* Enable Vrefbuf Clock */
  
  APP_ADCConfig();

  APP_ADCCalibrate();
  
  ADC1->CR |= ADC_CR_ADEN;

  while (1) /* Infinite loop */
  {     
    ADC1->CR |= ADC_CR_ADSTART; /* Start the ADC conversions */
    while ((ADC1->ISR & ADC_ISR_EOSEQ) == 0); /* wait end of conversion */
    ADC_Value = (ADC1->DR*2048) / 4095;
    ADC1->ISR = ADC_ISR_EOSEQ;
    APP_Delay(1000);
  }
}

/**
  * @brief   This function configure the ADC
  * @param   None
  * @retval  None
  */
static __INLINE void APP_ADCConfig(void)
{
  /* (1) Set the ADC Clock PCLK/8 */ 
  /* (2) Select the auto off mode */
  /* (3) Select a sampling mode of 111 i.e. 519.5 ADC clk */
  /* (4) Sequence Length 1 */
  /* (5) Enable Vrefbuf and Set Vrefsel */
  /* (6) ADC Select Vrefbuf */
  ADC1->CFGR2 = (ADC1->CFGR2 &~ (ADC_CFGR2_CKMODE)) | (ADC_CFGR2_CKMODE_1 | ADC_CFGR2_CKMODE_0); /* (1) */    
  ADC1->CFGR1 |= ADC_CFGR1_WAIT; /* (2) */
  ADC1->SMPR |= (ADC1->SMPR &~ (ADC_SMPR_SMP)) | (ADC_SMPR_SMP_0 | ADC_SMPR_SMP_1 | ADC_SMPR_SMP_2); /* (3) */
  ADC1->SQR1 = (ADC1->SQR1 &~ (ADC_SQR1_L | ADC_SQR1_SQ1)) | (ADC_SQR1_SQ1_0);    /* (4)  */
  
  VREFBUF->CR = (VREFBUF->CR &~ VREFBUF_CR_VREFBUF_OUT_SEL) | (VREFBUF_CR_VREFBUF_OUT_SEL_1) | VREFBUF_CR_VREFBUF_EN;  /* (5)  */

  ADC->CCR |= ADC_CCR_VREFEN | ADC_CCR_VREFSEL;   /* (6)  */
}

/**
  * @brief   This function performs a self-calibration of the ADC
  * @param   None
  * @retval  None
  */
static __INLINE void  APP_ADCCalibrate(void)
{
  /* (1) Set ADCAL=1 */
  /* (2) Set ADCAL_START=1 */
  /* (3) Wait until ADC_CR_ADCAL=0 */
  ADC1->CR |= ADC_CR_ADCAL; /* (1) */

  ADC1->CR |= ADC_CR_ADCAL_START; /* (2) */

  while ((ADC1->CR & ADC_CR_ADCAL) != 0) /* (3) */
  {
    /* For robust implementation, add here time-out management */
  }
}

/**
  * @brief   This function provides accurate delay (in milliseconds)
  * @param   Delay specifies the delay time length, in milliseconds.
  * @retval  None
  */
static __INLINE void APP_Delay(int32_t Delay)
{
  uint32_t tickstart = 0;
  tickstart = Tick;
  if (Delay  < 0xffffffff)
  {
    Delay ++;
  }
  while ((Tick - tickstart ) < (Delay)) 
  {

  }
}

/**
  * @brief  This function configures the system clock @8MHz 
  *         assuming the registers have their reset value before the call.
  *         SYSTEM CLOCK  = HSI DIV1
  *         FLASH LATENCY = 0
  * @param  None
  * @retval None
  */
static __INLINE void APP_SystemClockConfig(void)
{
  uint32_t tickstart = 0;
  /* (1) HSI DIV1 and Enable HSI */
  /* (2) Set HSI 8M and Triming Data */
  /* (3) Wait for HSI ready flag */
  /* (4) Set AHB divider:HCLK = SYSCLK */
  /* (5) Select HSISYS as system clock */
  /* (6) Wait for clock switched on HSI */
  /* (7) Set APB divider:PCLK = HCLK */

  RCC->CR = (RCC->CR &~(RCC_CR_HSIDIV)) | RCC_CR_HSION;                        /* (1) */

  RCC->ICSCR = (RCC->ICSCR & 0xFFFE0000) | (0 << RCC_ICSCR_HSI_FS_CR_Pos) | \
               ((*(uint32_t *)(0x1FFF0080)) & 0xFFFF);                         /* (2) */

  tickstart = Tick;
  while ((RCC->CR & (RCC_CR_HSIRDY)) != (RCC_CR_HSIRDY ))                      /* (3) */
  {
    if ((Tick - tickstart ) > HSI_TIMEOUT_VALUE)
    {
      error = ERROR_HSI_TIMEOUT; /* Report an error */
      return;
    }
  }

  RCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_HPRE));                                  /* (4) */

  RCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_SW)) | RCC_CFGR_SW_HSISYS;               /* (5) */
  tickstart = Tick;
  while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_HSISYS)                    /* (6) */
  {
    if ((Tick - tickstart ) > CLOCKSWITCH_TIMEOUT_VALUE)
    {
      error = ERROR_CLKSWITCH_TIMEOUT; /* Report an error */
      return;
    }
  }
 
  RCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_PPRE));                                  /* (7) */
}


/******************************************************************************/
/*            Cortex-M0 Plus Processor Exceptions Handlers                    */
/******************************************************************************/

/**
  * @brief  This function handles NMI exception.
  * @param  None
  * @retval None
  */
void NMI_Handler(void)
{
}

/**
  * @brief  This function handles Hard Fault exception.
  * @param  None
  * @retval None
  */
void HardFault_Handler(void)
{
  /* Go to infinite loop when Hard Fault exception occurs */
  while (1)
  {
  }
}

/**
  * @brief  This function handles SVCall exception.
  * @param  None
  * @retval None
  */
void SVC_Handler(void)
{
}

/**
  * @brief  This function handles PendSVC exception.
  * @param  None
  * @retval None
  */
void PendSV_Handler(void)
{
}


/**
  * @brief  This function handles SysTick Handler.
  * @param  None
  * @retval None
  */
void SysTick_Handler(void)
{
  Tick++;
}

/******************************************************************************/
/*                 MS32C001B Peripherals Interrupt Handlers                   */
/*  Add here the Interrupt Handler for the used peripheral(s) (PPP), for the  */
/*  available peripheral interrupt handler's name please refer to the startup */
/*  file (startup_ms32c001bxx.s).                                             */
/******************************************************************************/

/************************ (C) COPYRIGHT Puya *****END OF FILE******************/
