#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()
{
    // 1200, 2400, 4800, 9600, 14400, 19200, 38400, 43000, 57600, 76800, 115200, 128000, 230400
    const uint32_t baud_rate = 9600;
    s32 BaudRate_Par = 0;

    // 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 by baud_rate variable
    __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_DOUBLE_BAUD_RATE_X4);
    __DRV_URT0_Clock_Source_Timer2_Select(TRANSMIT_CLOCK_SOURCE_TIMER2_RECEIVE_CLOCK_SOURCE_TIMER2);
    BaudRate_Par = 256 - (s32)(3000000 / baud_rate);
    if (BaudRate_Par > 0)
    {
        __DRV_TIMER2_SetRCAP2L(BaudRate_Par);
    }
    else
    {
        __DRV_TIMER2_TL2_Clock_Source_Select(TIMER2_TL2_SPLIT_MODE_CLOCK_SOURCE_SYSCLK_DIV_12);
        BaudRate_Par = 256 - (s32)(250000 / baud_rate);
        if (BaudRate_Par > 0)
        {
            __DRV_TIMER2_SetRCAP2L(BaudRate_Par);
        }
        else
        {
            // Setting Error
        }
    }
    __DRV_TIMER_Globel_Enable_Cmd(TR2LE);
    while (1)
    {
        printf("Split mode T2OF as UART0 clock source successfully! Baud-Rate : %ld\n", (uint32_t)baud_rate);
        delay_ms(1000);
    }
}
