/********************************************************* * 
@file       :ks_int_test.c 
@brief      :keyscan interrupt 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_IntTestCase(void)
{
    uint32_t keyscanDiv = 50,keyscanCycle;
    uint32_t keyscanClk;

    NVIC_EnableIRQ(KSCAN_IRQn);

    uint32_t apb2Clk = CLK_GetPCLK1Freq();

    //keyscan clk adjust 
    //sclk < (1 / press_freq_max)/2  /((debounce+1)*max_row+frame_scan_interval)
    uint32_t halfPressCycle = (FREQ_1MHZ*1000) / KS_MAX_PRESS_FREQ / 2;

    uint32_t scanInterval = KS_GetFrameInterval(KSCAN);
	uint32_t rowInterval = KS_GetRowInterval(KSCAN);
    uint32_t debounceTime = KS_GetDebounceTime(KSCAN);
    debounceTime += 1;
    uint32_t clkTmp = (rowInterval + 3 + debounceTime) * KS_MAX_ROW + scanInterval + 3;

    do{
        //SET keyscan divider
        CLK_SetKeyscanDiv(keyscanDiv);  //2*N  div_100
        if(keyscanDiv) keyscanDiv *= 2;
        else keyscanDiv = 1;
        keyscanClk = apb2Clk / keyscanDiv;
        keyscanCycle = (FREQ_1MHZ*1000) / keyscanClk; //1s/freq(ns) 
        keyscanDiv -= 2;
    }while(keyscanCycle >= halfPressCycle/clkTmp);

    KS_IntEnable(KSCAN,ENABLE);
    KS_Enable(KSCAN,ENABLE,KS_PERIPHRAL_ENABLE);

    while(1) {
        char c = getchar();
        if(c == 0x1b)
            break;
    }
    return 0;
}
