/**
  ******************************************************************************
  * @file     Lib_ex_CMP2.c
  * @author   SINOMCU-AE
  * @brief    CMP config
  *    
  *          This file provides functions to CMP2 initialization.
  *         
  ******************************************************************************
  * @attention 
  *                           DISCLAIMER
  * The present firmware which is for guidance only aims at providing customers
  * with coding information regarding their products in order for them to save
  * time. As a result, SinoMCU shall not be held liable for any direct,indirect
  * or consequential damages with respect to any claims arising from the content 
  * of such firmware and/or the use made by customers of the coding information 
  * contained herein in connection with their products.
  *
  * <h2><center>&copy; Copyright (c) 2021 sinomcu All rights reserved.</center></h2>
  *
  ******************************************************************************
  */

#include "Lib_ex_CMP2.h"

/**
  * @brief  Initialize the CMP2 according to the specified
  *         parameters in the MS32_CMP_InitTypeDef and create the associated handle.
  * @param  CmpInitStr  pointer to a MS32_CMP_InitTypeDef structure that contains
  *                the configuration information for the specified CMP module.
  * @retval None
  */
void MS32_CMP2_Init(MS32_CMP_InitTypeDef *CmpInitStr) {
  uint32_t      reg_val = 0;
  __IO uint32_t delay_cnt;

  MS32_APB1_GRP2_EnableClock(MS32_APB1_GRP2_PERIPH_SYSCFG);

  // enable/disable vref and select voltage reference
  if (CmpInitStr->CrvSel == MS32_COMP_CRV_VREF) {
    SET_BIT(CMP_OP->CPANA, CMP_CPANA_CPVREFEN);
    SET_BIT(CMP_OP->CPANA, CMP_CPANA_CP2VOLT);
    delay_cnt = VREF_ANALOG_WAIT;
    while (delay_cnt--) { ; }
  } else {
     CLEAR_BIT(CMP_OP->CPANA, CMP_CPANA_CP2VOLT);
  }

  // auto calibration comparison 2 
  MS32_CMP2_Disable();
  SET_BIT(CMP_OP->CP2CAL, CMP_CPxCAL_CPxCALEN);
  while (READ_BIT(CMP_OP->CP2CAL, CMP_CPxCAL_CPxCALEN)) { ; }

  // set comparison 2
  if (CmpInitStr->PositionSel <= MS32_COMP_POS_CPx3P_PIN) {
    reg_val = MS32_COMP_POS_CPxP_PIN;
  } else {
    reg_val = CmpInitStr->PositionSel - 2;
  }
  reg_val |= (CmpInitStr->Lock      | CmpInitStr->OutputSel   | CmpInitStr->OutputPolarity | CmpInitStr->OutputFilter |\
              CmpInitStr->CrvDivSel | CmpInitStr->NegativeSel | CmpInitStr->PositionSel    | CmpInitStr->HysteresisSel);
  MODIFY_REG(CMP_OP->CP2CR, (CMP_CPxCR_CPxLCK   | CMP_CPxCR_CPxOUTSEL | CMP_CPxCR_CPxPOL  | CMP_CPxCR_CPxOFLT |\
                             CMP_CPxCR_CPxRVSEL | CMP_CPxCR_CPxNSEL   | CMP_CPxCR_CPxPSEL | CMP_CPxCR_CPxHYST), reg_val);
  MS32_CMP2_Enable();
}

/******************************** END OF FILE *********************************/
