/********************************************************* * 
@file       :ks_wakeup_test.c 
@brief      :keyscan wakeup function test
@author     :zhongfeng
@version    :v1.0 
@date       :19/10/28
Copyright (C) 2019 Panchip Technology Corp. All rights reserved. 
***********************************************************/
#include "pan271x.h"
#include "ks_common.h"


uint32_t KS_WakeUpTestCase4(void)
{
	uint32_t tmp_reg;
    uint32_t keyscanDiv = 2;
    uint32_t wake_cnt = 0;

	GPIO_DisablePullupPath(P2, BIT0 | BIT2);
	GPIO_DisablePullupPath(P1, BIT6);
	NVIC_EnableIRQ(LP_IRQn);
//	NVIC_EnableIRQ(SLPTMR_IRQn);

	uint32_t lpldo1 = 0x4;
	uint32_t lpldoh = 0x2;
	tmp_reg = PMU->ANA_LPLDO;
	tmp_reg &= ~ANA_LPLDO_PMU_LPLDOH_VSEL_AON_Msk;
	tmp_reg = (tmp_reg & ~(0xf << 20)) | (lpldoh << 20);
	PMU->ANA_LPLDO = tmp_reg;
	tmp_reg = PMU->ANA_RESERVED;
	tmp_reg &= ~ANA_RESERVED_PMU_LPLDOL_VSEL_AON_Msk;
	tmp_reg = (tmp_reg & ~(0xf<<17)) | (lpldo1 << 17);
	PMU->ANA_RESERVED = tmp_reg;

    KS_ClearKeyscanStatus(KSCAN,ENABLE);
    KS_Enable(KSCAN,ENABLE,KS_WAKEUP_AND_PERIPH_ENABLE);

	CLK_SetKeyscanClkSrc(CLKTRIM_KSCAN_CLK_SEL_32K);
    CLK_SetKeyscanDiv(keyscanDiv);

//    KS_SetFrameInterval(KSCAN,KS_INTERVAL_TIME_CLK_32);
	KS_SetDebounceTime(KSCAN,KS_INTERVAL_TIME_CLK_512);
//    KS_IntEnable(KSCAN,ENABLE);
    KS_Enable(KSCAN,ENABLE,KS_PERIPHRAL_ENABLE);

	GPIO_DisableDigitalPath(P0,BIT6);
	LP_SetOtpCeDelayTime(PMU, 0XA);
	LP_SetOtpPowerDelayTime(PMU, 0X2);
	LP_SetDeepSleepConfig(PMU,LP_WKUP_MODE_SEL_KSCAN,LP_DEEPSLEEP_MODE2);

    SYS_TEST("waked up, wake_cnt %d\n", ++wake_cnt);

    while(wake_cnt < 20) {
        SYS_TEST("Entering deepsleep again...\n");
		while(!wk_by_kscan_flag){}
		wk_by_kscan_flag = false;
		SYS_delay_10nop(100000);
        __WFI();
        SYS_TEST("waked up again, wake_cnt %d\n", ++wake_cnt);
    }

    return 0;
}
