/* task_user_key.c */
#include "app.h"

/* 实际连的是Touch芯片得IRQ引脚 */
#define GPIO_USER_KEY_PORT_IDX    1u //1u  //0u //1u
#define GPIO_USER_KEY_PIN_IDX     6u //18u //5u //6u

uint32_t gAppKeyValue = APP_USER_TASK_COUNT;/* 仅在初始化后出现一次 */

void App_InitUserKey(void)
{
    gpio_pin_config_t gpioPinConfig;

    //gAppKeyValue = APP_USER_KEY_VALUE_COUNT; /* initial value, for welcome page. */

    CLOCK_EnableClock(kCLOCK_Iocon); /* make sure the iocon clock is enabled. */
    IOCON_NS->PIO[GPIO_USER_KEY_PORT_IDX][GPIO_USER_KEY_PIN_IDX]
              = IOCON_PIO_DIGIMODE_MASK /* enable digital mode. */
              | IOCON_PIO_FUNC(0u)  /* setup GPIO mode. */
              | IOCON_PIO_MODE(0x2) /* enable Pull-up mode. */
              ;


    /* Setup the pin as input. */
    CLOCK_EnableClock(kCLOCK_Gpio1); /* make sure the clock is enabled. */
    CLOCK_EnableClock(kCLOCK_Gpio0); /* make sure the clock is enabled. */


    gpioPinConfig.pinDirection = kGPIO_DigitalInput;
    GPIO_PinInit(GPIO_NS, GPIO_USER_KEY_PORT_IDX, GPIO_USER_KEY_PIN_IDX, &gpioPinConfig);

    /* Setup the inputmux for PINT, using PINT0 here for the touch irq signal. */
    CLOCK_EnableClock(kCLOCK_InputMux);
    INPUTMUX_NS->PINTSEL[0] =  (GPIO_USER_KEY_PORT_IDX == 1u ? 32u : 0u )
                              + GPIO_USER_KEY_PIN_IDX;
    //CLOCK_DisableClock(kCLOCK_InputMux);

    /* Setup the interrupt for GPIO. */
    CLOCK_EnableClock(kCLOCK_Pint);

    /* Setup the trigger condition. */
    //PINT_NS->PMCFG = 0;           /* disable the pattern match engine. */
    PINT_NS->ISEL &= ~(1u << 0u); /* enable edge trigger. */
    PINT_NS->CIENR = (1u << 0u);  /* disable rising edge trigger. */
    PINT_NS->SIENF = (1u << 0u);  /* enable falling edge trigger. */
    PINT_NS->IST   = (1u << 0u);  /* clear flags. */

    /* Setup the NVIC. */
    NVIC_EnableIRQ(PIN_INT0_IRQn);
}

void App_DeinitUserKey(void)
{
    NVIC_DisableIRQ(PIN_INT0_IRQn);
}


uint32_t App_GetUserKeyValue(void)
{
    return gAppKeyValue;
}

/* PINT0 ISR
 *
 * . */
void PIN_INT0_IRQHandler(void)
{
    uint32_t flags = PINT_NS->IST;
    if (0u != ((1u << 0u) & PINT_NS->IST)) /* for pint0. */
    {
        /* delay for a while, as the anti-rebounce filter. */
        for (int i = 0u; i < 1000000; i++) { __NOP(); }

        /* Read the key value again for double check. */
        if ( 0u == GPIO_PinRead(GPIO_NS, GPIO_USER_KEY_PORT_IDX, GPIO_USER_KEY_PIN_IDX) )
        {
            if (gAppKeyValue >= APP_USER_TASK_COUNT)
            {
                gAppKeyValue = 0u;
            }
            else
            {
                gAppKeyValue = (gAppKeyValue + 1u) % APP_USER_TASK_COUNT;
            }
        }
    }
    PINT_NS->IST = flags;
}



/* EOF. */

