/**************************************************************************//**
 * @file     main.c
 * @version  V1.00
 * $Date: 19/10/30 16:17 $
 * @brief    Blinky Sample Code.
 * @note
 * Copyright (C) 2025 Panchip Technology Corp. All rights reserved.
 *
 ******************************************************************************/
#include "pan271x.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 |= SYS_CLK_CTRL_OTP_SW_UP_CYCLE_EN_Msk;

    PMU->ANA_ANALDO |= ANA_ANALDO_EN_LDO_FSYN_AON_Msk;

    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_RefClkSrcConfig(CLK_SYS_SRCSEL_XTH);

    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 LED_IoInit(void)
{
    SYS_SET_MFP(P0, 4, GPIO);
    GPIO_SetMode(P0, BIT4, GPIO_MODE_OUTPUT);

    /* Set P04 to low */
    GPIO_WritePin(0, 4, 0);
}

int main(void)
{
    platform_init();

    SYS_TEST("\nCPU @ %dHz\n", SystemCoreClock);

    // Init LED on EVB
    LED_IoInit();

    // Toggle GPIO P04 output level
    while (1) {
        SYS_delay_10nop(1000000);
        GPIO_WritePin(0, 4, 1);
        SYS_TEST("LED on\n");
        SYS_delay_10nop(1000000);
        GPIO_WritePin(0, 4, 0);
        SYS_TEST("LED off\n");
    }
}
