/******************************************************************************
 * @file     main.c
 * @brief    Main program body
 * @version  V1.8.0
 * @date     31-Dec-2021
 *
 * @note
 * Copyright (C) 2021 Spintrol Limited Corporation. All rights reserved.
 *
 * @attention
 * THIS SOFTWARE JUST PROVIDES CUSTOMERS WITH CODING INFORMATION REGARDING
 * THEIR PRODUCTS, WHICH AIMS AT SAVING TIME FOR THEM. SPINTROL SHALL NOT BE
 * LIABLE FOR THE USE OF THE SOFTWARE. SPINTROL DOES NOT GUARANTEE THE
 * CORRECTNESS OF THIS SOFTWARE AND RESERVES THE RIGHT TO MODIFY THE SOFTWARE
 * WITHOUT NOTIFICATION.
 *
 ******************************************************************************/

#include"spc1168.h"
#include<stdio.h>

/**
 *  @brief  Variable for comparator status register value.
 */
uint32_t u32status = 0;


 /*************************************************************************************************************************
 *
 * @brief      In this case, if the value of ADC8 is bigger than the reference voltage, the print will be "The comparator is
 *             higher than low-boundary", otherwise, "The comparator is lower than low-boundary".
 *
 *************************************************************************************************************************/


int main()
{
  FLASH_WALLOW();
  FLASH_SetTiming(200000000);
  /* Disable flash write access after flash operation had done */
  FLASH_WDIS();

  CLOCK_InitWithRCO(CLOCK_HCLK_200MHZ);

  Delay_Init();

  /*
   * Init the UART
   *
   * 1.Set the GPIO34/35 as UART FUNC
   *
   * 2.Enable the UART CLK
   *
   * 3.Set the rest para
   */
  GPIO_SetPinChannel(GPIO_34,GPIO34_UART_TXD);
  GPIO_SetPinChannel(GPIO_35,GPIO35_UART_RXD);
  CLOCK_EnableModule(UART_MODULE);
  UART_Init(UART,38400);

  /* 
   * Configure Comparator.
   *
   * 1.Set low detection.
   *
   * 2.Set ADC8 as the input.
   *
   * 3.Set DAC as 1500mV for low voltage detecting reference voltage.
   *
   * 4.Set the DigitaL Filter as 25ns, in order to filter the noise.
   */
  COMP_Init(COMP_0_LO,COMP0_FROM_ADC8,1000,25);

  /* Set high detection for ADC8 and reference value is 2000mV */
  COMP_Init(COMP_0_HI,COMP0_FROM_ADC8,2000,25);

  while(1)
  {
    /* Get the comparator status */
    u32status = COMP_GetFilterOutputStatus(COMP_0_HI);
    if(u32status & 0x1)
    {
      COMP_ClearAllFilterOutputStatus();
      printf("The target voltage is higher than high-boundary of comparator\n");
    }
    
    u32status = 0;
    u32status = COMP_GetFilterOutputStatus(COMP_0_LO);
    if(u32status & 0x1)
    {
      COMP_ClearAllFilterOutputStatus();
      printf("The target voltage is lower than low-boundary of comparator\n");
    }

    Delay_Ms(500);
  }
}
