#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"

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

/****************************************************************
 *  Delay function
 *  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()
{
    // 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 38400
    __DRV_TIMER2_Mode_Select(TIMER2_SPLIT_MODE1_TWO_8BIT_AUTORELOAD_WITH_EXTERNAL_INTERRUPT);
    __DRV_TIMER2_TL2_Clock_Source_Select(TIMER2_TL2_SPLIT_MODE_CLOCK_SOURCE_SYSCLK);
    __DRV_URT0_BaudRateX2X4_Select(UART0_DEFAULT_BAUD_RATE);
    __DRV_URT0_Clock_Source_Timer2_Select(TRANSMIT_CLOCK_SOURCE_TIMER2_RECEIVE_CLOCK_SOURCE_TIMER2);
    __DRV_TIMER2_SetLowByte(236);
    __DRV_TIMER2_SetRCAP2L(236);
    __DRV_TIMER_Globel_Enable_Cmd(TR2LE);
    while (1)
    {
        printf("Split mode T2OF as UART0 clock source successfully! Baud-Rate : 38400\n");
        delay_ms(1000);
    }
}
