/******************************************************************************
 * @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      In this case, GPIO30 ouput a rising edge, GPIO30 connecting with GPIO31 will detect this rising edge, 
 *             coressponding information will ba print when ever rising edge happened or not.
 *
 *************************************************************************************************************************/


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);

  /* Set GPIO31/GPIO30 as GPIO FUNC */
  GPIO_SetPinAsGPIO(GPIO_31);
  GPIO_SetPinAsGPIO(GPIO_30);

  /* Set GPIO31/GPIO30 direction */
  GPIO_SetPinDir(GPIO_31,GPIO_OUTPUT);
  GPIO_SetPinDir(GPIO_30,GPIO_INPUT);

  /* 
   * De-glitch settings, if IO signal state can keep 128 PCLK cycles, 
   * then it will will be assumed valid 
   */
  GPIO_SetDeglitchWindow(0x7);
  GPIO_EnableDeglitch(GPIO_30);


  /* GPIO INT configuration: rising edge will trigger INT */
  GPIO_SetEdgeIntMode(GPIO_30, GPIO_INT_RISING_EDGE);
  GPIO_EnableEdgeInt(GPIO_30);

  /* Enable GPIO edge trigger INT in CPU side */
  NVIC_EnableIRQ(GPIO_EDGE_IRQn);

  /* Generate a rising edge */
  GPIO_WritePin(GPIO_31,GPIO_LEVEL_LOW);
  Delay_Ms(100);
  GPIO_TogglePin(GPIO_31);

  while(1)
  {

  }
}

void GPIO_EDGE_IRQHandler()
{
  int iResult = -1;

  /* Checking if Edge had detected */
  iResult = GPIO_GetEdgeIntStatus(GPIO_30);
  if(iResult == 1)
    printf("Rising edge had detected\n");
  else
    printf("No rising edge, test failed\n");

  /* Clear GPIO INT */
  GPIO_ClearEdgeInt(GPIO_30);
  
  GPIO_ClearGlobalEdgeInt();
}
