/****************************************************************************
 * @file     main.c
 * @version  V1.00
 * $Revision: 1 $
 * $Date: 16/02/ 10:37 $
 * @brief    Main file of the key scan sample project.
 *
 * @note
 * Copyright (C) 2016 Shanghai Panchip Microelectronics Co., Ltd.   All rights reserved.
 *
 ******************************************************************************/
#include "pan271x.h"
#include "ks_common.h"


void Clock_Init(void)
{
	PMU->SYS_CLK_CTRL |= SYS_CLK_CTRL_OTP_READ_MODE_SEL_Msk;
	PMU->SYS_CLK_CTRL &= ~(SYS_CLK_CTRL_OTP_CLK_HIGH_CYCLE_Msk | SYS_CLK_CTRL_OTP_CLK_LOW_CYCLE_Msk);
	PMU->SYS_CLK_CTRL |= ((0x1 << SYS_CLK_CTRL_OTP_CLK_HIGH_CYCLE_Pos) | (0x0 << SYS_CLK_CTRL_OTP_CLK_LOW_CYCLE_Pos));
	PMU->SYS_CLK_CTRL |= SYS_CLK_CTRL_OTP_SW_UP_CYCLE_EN_Msk;

	PMU->ANA_ANALDO |= ANA_ANALDO_EN_LDO_FSYN_AON_Msk;
    //MCU
	CLK_XthStartupConfig();
	PMU->XTH_CTRL |= XTH_CTRL_FSYNXO_BUFEN_AON_Msk;
    PMU->XTH_CTRL |= XTH_CTRL_FSYNXO_EN_AON_Msk;
	CLK_WaitClockReady(CLK_SYS_SRCSEL_XTH);

	CLK_HCLKConfig(0);

	CLK_SYSCLKConfig(CLK_DPLL_REF_CLKSEL_XTH,CLK_DPLL_OUT_48M); 
	CLK_RefClkSrcConfig(CLK_SYS_SRCSEL_DPLL_1);

	CLK_AHBPeriphClockCmd(CLK_AHBPeriph_All,ENABLE);
	CLK_APB1PeriphClockCmd(CLK_APB1Periph_All,ENABLE);
}

void Peri_Init(void)
{
    SYS_UnlockReg();

    /* Init I/O Multi-function  */
	SYS_SET_MFP(P0,6,UART0_RX);
	SYS_SET_MFP(P0,5,UART0_TX);
	GPIO_EnableDigitalPath(P0,BIT6);

	UART_Init(UART0, 115200);
	
    SYS_LockReg();
}

void platform_init()
{	
    Clock_Init();
    Peri_Init();
}

void KS_PrintSampleInfo()
{
    SYS_TEST("\n");
    SYS_TEST("+-----------------------------------------------------------------------------+ \n");
    SYS_TEST("|                      PAN271x KeyScan Sample Code.                            | \n");
    SYS_TEST("+-----------------------------------------------------------------------------+ \n");
    SYS_TEST("|    Press key to start specific testcase:                                    | \n");
    SYS_TEST("|                                                                             | \n");
    SYS_TEST("|    Input '1'    Testcase 1: key int Test Case.                              | \n");
    SYS_TEST("|    Input '2'    Testcase 2: key polling Test Case.                          | \n");
    SYS_TEST("+-----------------------------------------------------------------------------+ \n");
}

int main(void)
{
    char input;

    platform_init();

    KS_TestModuleInit();

    SYS_TEST("\nCPU @ %dHz\n", SystemCoreClock);
    KS_PrintSampleInfo();
    input = getchar();
    while(input){
        SYS_TEST("\r\n");
        switch(input){
            case '1':KS_TestFunctionEnter(0);break;
            case '2':KS_TestFunctionEnter(1);break;
            default:break;
        }
        KS_PrintSampleInfo();
        input = getchar();
    }
    while(1);
}
