


/**
 ******************************************************************************
 *
 * @file        BSP_UARTCOM.c
 * @brief       UART initial and mapping printf function.
 *
 * @par         Project
 *              MG32x02z
 * @version     V1.01
 * @date        2022/08/01
 * @author      Megawin Software Center
 * @copyright   Copyright (c) 2017 MegaWin Technology Co., Ltd.
 *              All rights reserved.
 * 
 ******************************************************************************* 
 * @par Disclaimer
 * The Demo software is provided "AS IS" without any warranty, either
 * expressed or implied, including, but not limited to, the implied warranties
 * of merchantability and fitness for a particular purpose. The author will
 * not be liable for any special, incidental, consequential or indirect
 * damages due to loss of data or any other reason.
 * These statements agree with the world wide and local dictated laws about
 * authorship and violence against these laws.
 *******************************************************************************
 *******************************************************************************
 */

/*==============================================================================
                                 User NOTES
How To use this function:
   + After BSP_UARTCom_Init() complete , user can use "printf" to output data.
   + If want control own parameter after BSP_UARTCom_Init(),you can write 
     BSP_InitCallback() to replace.
Driver architecture:
--------------------
   + MG32x02z_GPIO_DRV
   + MG32x02z_URT_DRV
   
Known Limitations:
------------------   
   +. Run in 48MHz (APB clock)
   +. Change URT_PSR, URT_RLR and URT_OS to change UART baud-rate.
      ( URT_PSR, URT_RLR and URT_OS define in BSP_UARTCOM.h")  
   +. UART baud-rate = f (APB) / ( (URT_PSR + 1) * (URT_RLR + 1) * (URT_OS + 1))
   
==============================================================================*/


/* Includes ------------------------------------------------------------------*/
#include "BSP_UARTCOM.h"

/* Wizard menu ---------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported variables --------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/* External variables --------------------------------------------------------*/



/**
 *******************************************************************************
 * @brief	   UART Initial (URT4)
 * @details    Using UART driver to initial the UART( Baud-Rate = 115200 in URT 
               input clock is 48MHz.
 * @return      
 * @exception   
 * @note       URTX define in BSP_UARTCOM.h                 
 *******************************************************************************
 */
void BSP_UARTCom_Init(void)
{
    
    URT_BRG_TypeDef  BSP_URTCom_BRG;
    
    /*GPIO Initial*/
    BSP_GPIO_PinConfig( URT_TXD_IOM, Data_DIR_OUT_PP, URT_TXD_AFS);
    BSP_GPIO_PinConfig( URT_RXD_IOM, Data_DIR_IN_RU, URT_RXD_AFS);
    
    /*Set Baud-Rate*/
    BSP_URTCom_BRG.URT_InternalClockSource    = URT_BDClock_PROC;     //URT clock from CK_URT_PR
    BSP_URTCom_BRG.URT_BaudRateMode           = URT_BDMode_Separated;     
    BSP_URTCom_BRG.URT_PrescalerCounterReload = URT_PSR;	          //Set PSR
    BSP_URTCom_BRG.URT_BaudRateCounterReload  = URT_RLR;	          //Set RLR
    URT_BaudRateGenerator_Config(URTX, &BSP_URTCom_BRG);		      //BR115200 in CK_URT_PR = 48MHz ( f(CK_URTx)/(PSR+1)/(RLR+1)/(OS_NUM+1) )
    URT_BaudRateGenerator_Cmd(URTX, ENABLE);	                      //Enable BaudRateGenerator
    URT_TXClockSource_Select(URTX, URT_TXClock_Internal);	          //URT_TX use BaudRateGenerator
    URT_RXClockSource_Select(URTX, URT_RXClock_Internal);	          //URT_RX use BaudRateGenerator
    URT_TXOverSamplingSampleNumber_Select(URTX, URT_OS);	          //Set TX OS_NUM
    URT_RXOverSamplingSampleNumber_Select(URTX, URT_OS);	          //Set RX OS_NUM
    URT_RXOverSamplingMode_Select(URTX, URT_RXSMP_3TIME);
    
    /*Enable RX / TX function.*/
    URT_TX_Cmd(URTX, ENABLE);	                                      //Enable TX
    URT_RX_Cmd(URTX, ENABLE);	                                      //Enable RX
    
    /*Character format*/
    //Character format
    // - Data bit     : 8 bit
    // - Dart order   : LSB
    // - Parity bit   : No
    // - Stop bit     : 1 bit
    // - Data inverse : No
    URTX->CR1.B[2] = (((uint8_t)URT_DataLength_8)  | 
                      ((uint8_t)URT_DataTyped_LSB) | 
                      ((uint8_t)URT_Parity_No)     | 
                      ((uint8_t)URT_StopBits_1_0));
    
    URTX->CR1.B[0] = (((uint8_t)URT_DataLength_8)  | 
                      ((uint8_t)URT_DataTyped_LSB) | 
                      ((uint8_t)URT_Parity_No)     | 
                      ((uint8_t)URT_StopBits_1_0));
    
    //RX / TX Data bit no inverse.
    URTX->CR4.B[0] = (URTX->CR4.B[0] & (~(URT_CR4_RDAT_INV_mask_b0|URT_CR4_TDAT_INV_mask_b0)));
                     
    /*Set Mode*/
    //URT mode is UART.
    URT_Mode_Select(URTX, URT_URT_mode);
    //URT data line is 2 line.
    URT_DataLine_Select(URTX, URT_DataLine_2);
    //URT RX shadow buffer threshold is 1 byte.
    URT_RXShadowBufferThreshold_Select(URTX, URT_RXTH_1BYTE);
    //No idle mode.
    URT_IdlehandleMode_Select(URTX, URT_IDLEMode_No);
    //Gaud Time is 0 byte.
    URT_TXGuardTime_Select(URTX, 0);
    //Clear URT flag.
    URT_ClearITFlag(URTX,URT_IT_Mask);
    //Clear TX buffer.
    URT_ClearTXData(URTX);
    //Enable URT.
    URT_Cmd(URTX, ENABLE);
    
    BSP_InitCallback();
    
}

/*
 *******************************************************************************
 * @brief       writes the character specified by c (converted to an unsigned char) to
 *              the output stream pointed to by stream, at the position indicated by the
 *              asociated file position indicator (if defined), and advances the
 *              indicator appropriately. If the file position indicator is not defined,
 *              the character is appended to the output stream.
 * @param[in]   ch
 * @param[in]   f
 * @return      the character written. If a write error occurs, the error
 *              indicator is set and fputc returns EOF.
 *******************************************************************************
 */
int fputc(int ch, FILE *f __attribute__((unused)))
{
    URTX->TDAT.B[0] = (uint8_t)ch;
    while((URTX->STA.W & URT_STA_TXF_mask_w) == 0);
    
    return ch;
}


/**
 *******************************************************************************
 * @brief       obtains the next character (if present) as an unsigned char converted to
 *              an int, from the input stream pointed to by stream, and advances the
 *              associated file position indicator (if defined).
 * @param[in]   f
 * @return      the next character from the input stream pointed to by stream.
 *              If the stream is at end-of-file, the end-of-file indicator is
 *              set and fgetc returns EOF. If a read error occurs, the error
 *              indicator is set and fgetc returns EOF.
 *******************************************************************************
 */
int fgetc(FILE *f)
{
    uint8_t ch;
    
    ((void)(f));
    
    while(URT0->STA.MBIT.RXF == 0);
    ch = URT0->RDAT.B[0];
    
    return ((int)ch);
}

/**
 *******************************************************************************
 * @brief	   BSP Initial callback function 
 * @details     
 * @return      
 * @exception   
 * @note                        
 *******************************************************************************
 */
__WEAK void BSP_InitCallback(void)
{
    //=========================================================
    //NOTE : This function should not be modifyed, when the 
    //       callback is needed, the MID_URT_RxCpltCallback 
    //       can be implemented in the user file.

}




