/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.2
 *
 * @date        2023-03-31
 *
 * @attention
 *
 *  Copyright (C) 2023 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE).
 *
 *  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 SOFTWARE PACKAGE LICENSE for the governing permissions
 *  and limitations under the License.
 */

/* Includes */
#include "main.h"

/** @addtogroup Examples
  @{
*/

/** @addtogroup TMR2_SinglePulse
  @{
*/

/** @defgroup TMR2_SinglePulse_Functions Functions
  @{
*/

/* TMR2 Init */
void TMR2_Init(void);
/* Key process */
BOOL KeyPressed(void);

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 */
int main(void)
{
    APM_MINI_LEDInit(LED2);
    APM_MINI_LEDInit(LED3);
    APM_DelayInit(APM_DELAY_MS);
    APM_MINI_PBInit(BUTTON_KEY1, BUTTON_MODE_GPIO);

    TMR2_Init();

    while(1)
    {
        if(KeyPressed())
        {
            TMR2_Enable();
        }
    }
}

/*!
 * @brief       TMR2 Init
 *
 * @param       None
 *
 * @retval      None
 */
void TMR2_Init(void)
{
    TMR2_OCConfig_T ocConfigStruct;
    GPIO_Config_T gpio_struct;

    gpio_struct.pin = GPIO_PIN_3;
    gpio_struct.speed = GPIO_SPEED_10MHz;
    gpio_struct.mode = GPIO_MODE_OUT_PP;
    gpio_struct.intEn = GPIO_EINT_DISABLE;

    GPIO_Config(GPIOA, &gpio_struct);

    /* Set counter = 0XFF, divider = 4 */
    TMR2_ConfigTimerBase(47, 500);

    /* CH3 output one pulse */
    ocConfigStruct.channel = TMR2_CHANNEL_3;
    ocConfigStruct.count = 250;
    ocConfigStruct.mode = TMR2_OC_MODE_PWM1;
    ocConfigStruct.OCxOutputState = TMR2_OC_OUTPUT_ENABLE;
    ocConfigStruct.OCxPolarity = TMR2_OC_POLARITY_HIGH;
    TMR2_ConfigOutputCompare(&ocConfigStruct);

    TMR2_EnableSinglePulseMode();

    /* Enable TMR2  */
    TMR2_Enable();
}

/*!
 * @brief       Check Key is pressed
 *
 * @param       None
 *
 * @retval      Return TRUE if key has been pressed else return FALSE
 */
BOOL KeyPressed(void)
{
    BOOL ret = FALSE;

    if(APM_MINI_ReadPBState(BUTTON_KEY1) == BIT_RESET)
    {
        APM_Delay(50);
        if(APM_MINI_ReadPBState(BUTTON_KEY1) == BIT_RESET)
        {
            while(APM_MINI_ReadPBState(BUTTON_KEY1) == BIT_RESET);

            ret = TRUE;
        }
    }

    return ret;
}

/**@} end of group TMR2_SinglePulse_Functions */
/**@} end of group TMR2_SinglePulse */
/**@} end of group Examples */
