/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.0
 *
 * @date        2026-02-25
 *
 * @attention
 *
 *  Copyright (C) 2026 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (Geehy Semiconductor Software License Agreement).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be useful and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the Geehy Semiconductor Software License Agreement for the governing permissions
 *  and limitations under the License.
 */

/* Includes */
#include "user_tmr_config.h"
#include "Board.h"
#include "stdio.h"

/** @addtogroup Examples
  @{
*/

/** @addtogroup TMR_Examples
@{
*/

/** @addtogroup TMR_TimeBase
  @{
*/

/** @defgroup TMR_TimeBase_Variables Variables
  @{
*/

/* Timer g_tick */
static volatile uint32_t g_tick = 0;

/**@} end of group TMR_TimeBase_Variables */

/** @defgroup TMR_TimeBase_Functions
  @{
  */

/* TMR2 Init */
void Tmr2_Init(void);

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
int main(void)
{
    Board_ButtonInit(BUTTON_KEY1, BUTTON_MODE_EINT);
    Board_LedInit(LED2);
    Board_LedInit(LED3);
    Tmr2_Init();

    /* Turn LED2 on */
    Gpio_ClearBit(LED2_GPIO_PORT, (uint16_t)LED2_PIN);
    /* Turn LED3 off */
    Gpio_SetBit(LED3_GPIO_PORT, (uint16_t)LED3_PIN);

    for (;;)
    {
        if (g_tick >= (uint32_t)1000)
        {
            g_tick = 0;
            Board_LedToggle(LED2);
            Board_LedToggle(LED3);
        }
        else
        {
            /* nothing */
        }
    }
}


void Tmr2_Init(void)
{
    /* Enable Clock */
    Rcm_EnableApb2PeriphClock(RCM_APB2_PERIPH_SYSCFG);
    Rcm_EnableApb1PeriphClock(RCM_APB1_PERIPH_TMR2);

    Tmr_ConfigTimeBase(TMR2, &g_tmr2_BaseConfig);

    /* Enable update interrupt*/
    Tmr_EnableInterrupt(TMR2, (uint16_t)TMR_INT_UPDATE);
    Nvic_EnableIrqRequest(TMR2_IRQn, 2);

    /*  Enable TMR2  */
    Tmr_Enable(TMR2);
}

/*!
 * @brief       TMR2 interrupt service runtine
 *
 * @param       None
 *
 * @retval      None
 *
 * @note        This function need to put into TMR2_IRQHandler() in g32a10xx_int.c
 */
void Tmr2_Isr(void)
{
    if (Tmr_ReadIntFlag(TMR2, TMR_INT_FLAG_UPDATE) == (uint16_t)SET)
    {
        /* The interrupt flag bit must be cleared first. */
        Tmr_ClearIntFlag(TMR2, (uint16_t)TMR_INT_FLAG_UPDATE);
        
        g_tick = g_tick + (uint32_t)1u;
    }
    else
    {
        /* nothing */
    }
}

/**@} end of group TMR_TimeBase_Functions */
/**@} end of group TMR_TimeBase */
/**@} end of group TMR_Examples */
/**@} end of group Examples */
