#include <intrins.h>
#include "REG_MG82F6D64.h"
#include "TYPEDEF.h"
#include "stdio.h"
#include "MG82F6D64_COMMON_DRV.h"
#include "MG82F6D64_GPIO_DRV.h"
#include "MG82F6D64_Timer_DRV.h"
#include "MG82F6D64_UART0_DRV.h"
#include "MG82F6D64_CLK_DRV.h"

/**
 ******************************************************************************
 * do-while template
 ******************************************************************************
 */
#define MWT( __stuff__ )  do { __stuff__ } while (0)

/****************************************************************
 *  Function : delay_ms
 *  When CPU clock at 12 MHz delay time is about 1mS.
 ****************************************************************/
void delay_ms(uint16_t dly)
{
    uint16_t dly1;
    while (dly--)
    {
        dly1 = 627;
        while (dly1--);
    }
}

void main()
{
    /****************************************************************
     *  SYSCLK Initialized
     *  1. Setting clock source at 48MHz
     ****************************************************************/
    __DRV_CLK_PLL_Enable();
    __DRV_CLK_MCK_Select(MCK_CKMI_X8X12);

    // UART0 Register initial Tx:P31 Rx:P30
    __DRV_URT0_SetSM10(UART0_MODE1_8BIT);
    __DRV_URT0_SerialReception_Cmd(MW_ENABLE);
    TI0 = 1;

    // Use Timer2 Auto reload mode to generate the baud rate 256000
    __DRV_TIMER2_Mode_Select(TIMER2_MODE1_16BIT_AUTORELOAD_WITH_EXTERNAL_INTERRUPT);
    __DRV_TIMER2_Clock_Source_Select(TIMER2_CLOCK_SOURCE_SYSCLK);
    __DRV_URT0_BaudRateX2X4_Select(UART0_DOUBLE_BAUD_RATE_X4);
    __DRV_URT0_Clock_Source_Timer2_Select(TRANSMIT_CLOCK_SOURCE_TIMER2_RECEIVE_CLOCK_SOURCE_TIMER2);
    __DRV_TIMER2_Set16Bit_AutoReloadValue(65489);
    __DRV_TIMER2_Run_Cmd(MW_ENABLE);

    while (1)
    {
        printf("T2OF as UART0 clock source successfully! Baud-Rate : 256000\n");
        delay_ms(1000);
    }
}
