/********************************************************************

UART.c

This file implements the io_putchar and io_getchar functions
for all the STRx devices.

It is the source code for the IO_Putchar.a default library.

It has been written by using the ST libs and then inlining and
simplifying the code for optimization.

You can duplicate it and include the copy in your project,
then you'll be able to modify it for using different parameters:
baudrate, stop bits, other UART, etc.

*********************************************************************/



#include "str9x.h"

#define __UART0 0x8
#define __GPIO3 0x20000
#define RESET 0

unsigned char __io_init_done = 0;


unsigned int __io_Main_Osc = 25000000;

//called by the user app to tell us what is the main osc frequency
void __io_SetMainOscFreq( unsigned int NewFreq )
    {
    __io_Main_Osc=NewFreq; //save new freq value
    __io_init_done = 0; //force reinit at next putchar
    }


void __io_init( void )
    { 
    // Configure the GPIO pins

		// P3.0 and P3.1

    //GPIO_InitTypeDef gpio_init;
    //UART_InitTypeDef uart_init;

    /* Enable the UART0 Clock */
    //SCU_APBPeriphClockConfig(__UART0, ENABLE);
    SCU->PCGR1 |=__UART0;

    /* Enable the GPIO3 Clock */
    //SCU_APBPeriphClockConfig(__GPIO3, ENABLE);
    SCU->PCGRO |=__GPIO3;

    //GPIO_DeInit(GPIO3);
    SCU->PRR1 &=~__GPIO3;
    SCU->PRR1 |=__GPIO3;
    SCU->GPIOTYPE[0x03] = 0x0000 ;
    SCU->GPIOOUT[0x03]  = 0x0000;
    SCU->GPIOIN[0x03]   = 0x0000;

    /*Configure UART0_Rx pin GPIO3.0*/
    /* Select pin direction */
    GPIO3->DIR &= ~1;

    /*Output ALternate 0*/
    SCU->GPIOOUT[3] &= ~0x3;

    /*Type configuration: PushPull or Open Collector*/
    SCU->GPIOTYPE[3] &= ~0x1;

    /*IP Connected disable*/
    SCU->GPIOIN[3] &= ~0x1;
    /*IP Connected enable*/
    SCU->GPIOIN[3] |= 0x1;

    /*Configure UART0_Tx pin GPIO3.1*/
    GPIO3->DIR |= 2;

    /*Output ALternate 0*/
    SCU->GPIOOUT[3] &= ~(0xC);

    /*Output ALternate 2*/
    SCU->GPIOOUT[3] |= 0x8;

    /*Type configuration: PushPull or Open Collector*/
    SCU->GPIOTYPE[3] &= ~(0x2) ;

    /*IP Connected disable*/
    SCU->GPIOIN[3] &= ~(0x2) ;
    /*IP Connected enable*/
    SCU->GPIOIN[3] |= 0x2;

    //UART_DeInit(UART0);
    /* Reset the UARTx registers values */
    //SCU_APBPeriphReset(__UART0,ENABLE);
    SCU->PRR1 &=~__UART0;                   /*APB peripheral held in Reset*/
    //SCU_APBPeriphReset(__UART0,DISABLE);
    SCU->PRR1 |=__UART0;

#define UART_IrDA_Disable_Mask	        0xFFFD	/* IrDA Disable Mask */
#define UART_IrDA_Enable_Mask           0x0002	/* IrDA Enable Mask */
#define IrDA_LowPower_Enable_Mask       0x0004 /*IrDA lower power mode enable*/
#define IrDA_LowPower_Disable_Mask      0xFFFB /*IrDA lower power mode enable*/

    /* UART Mask */
#define UART_Enable_Mask	        0x0001	/* UART Enable Mask */
#define UART_Disable_Mask	        0xFFFE	/* UART Disable Mask */

    /* UART LoopBack */
#define UART_LoopBack_Disable_Mask      0xFF7F	/* LoopBack Disable Mask */
#define UART_LoopBack_Enable_Mask       0x0080	/* LoopBack Enable Mask */

#define UART_WordLength_Mask            0xFF9F  /* UART Word Length Mask */
#define UART_Parity_Mask                0xFF79  /* UART Parity Mask */
#define UART_HardwareFlowControl_Mask   0x3FFF  /* UART Hardware Flow Control Mask */
#define UART_TxRxFIFOLevel_Mask         0xFFC0  /* UART Tx Rx FIFO Level Mask */
#define UART_BreakChar_Mask             0x0001  /* UART Break Character send Mask*/
#define UART_FLAG_Mask                  0x1F    /* UART Flag Mask */
#define UART_Mode_Mask                  0xFCFF  /* UART Mode Mask */
#define UART_RTS_LowLevel_Mask          0x0800  /* RTS signal is low */
#define UART_RTS_HighLevel_Mask         0xF7FF  /* RTS signal is High */
#define UART_DTR_LowLevel_Mask          0x0400  /* DTR signal is low */
#define UART_DTR_HighLevel_Mask         0xFBFF  /* DTR signal is High */
#define UART_ClearFlag_Mask             0xAA    /* Clear Flag Mask */

    /* UART Data Length */
#define UART_WordLength_5D	      0x0000  /* 5 bits Data */
#define UART_WordLength_6D	      0x0020  /* 6 bits Data */
#define UART_WordLength_7D	      0x0040  /* 7 bits Data */
#define UART_WordLength_8D	      0x0060  /* 8 bits Data */

    /* UART Stop Bits */
#define UART_StopBits_1         0xFFF7  /* Disable two stop bit is transmitted
    at the end of frame */
#define UART_StopBits_2         0x0008  /* Enable Two stop bits are transmitted
    at the end of frame */
    /* UART Parity */
#define UART_Parity_No	              0x0000  /* Parity Disable */
#define UART_Parity_Even	      0x0006  /* Even Parity */
#define UART_Parity_Odd	              0x0002  /* Odd Parity */
#define UART_Parity_OddStick	      0x0082  /* 1 is transmitted as bit parity */
#define UART_Parity_EvenStick	      0x0086  /* 0 is transmitted as bit parity */

    /* UART Hardware Flow Control */
#define UART_HardwareFlowControl_None	   0x0000  /* HFC Disable */
#define UART_HardwareFlowControl_RTS	   0x4000  /* RTS Enable */
#define UART_HardwareFlowControl_CTS	   0x8000  /* CTS Enable */
#define UART_HardwareFlowControl_RTS_CTS   0xC000  /* CTS and RTS Enable */

    /* UART Mode */
#define UART_Mode_Rx                  0x0200  /* UART Rx Enabled */
#define UART_Mode_Tx                  0x0100  /* UART Tx Enbled */
#define UART_Mode_Tx_Rx               0x0300  /* UART Tx and Rx Enabled */

    /* UART FIFO */
#define UART_FIFO_Disable           0xFFEF  /* FIFOs Disable */
#define UART_FIFO_Enable            0x0010  /* FIFOs Enable */

    /* UART Interrupt definition */
#define UART_IT_OverrunError	      0x0400  /* Overrun Error interrupt mask */
#define UART_IT_BreakError	      0x0200  /* Break Error interrupt mask */
#define UART_IT_ParityError	      0x0100  /* Parity Error interrupt mask */
#define UART_IT_FrameError	      0x0080  /* Frame Error interrupt mask */
#define UART_IT_ReceiveTimeOut	      0x0040  /* Receive Time Out interrupt mask */
#define UART_IT_Transmit              0x0020  /* Transmit interrupt mask */
#define UART_IT_Receive	              0x0010  /* Receive interrupt mask */
#define UART_IT_DSR	              0x0008  /* DSR interrupt mask */
#define UART_IT_DCD	              0x0004  /* DCD interrupt mask */
#define UART_IT_CTS	              0x0002  /* CTS interrupt mask */
#define UART_IT_RI	              0x0001  /* RI interrupt mask */

    /* UART DMA On Error */
#define UART_DMAOnError_Enable	      0xFFFB  /* DMA receive request enabled
    when the UART error interrupt
    is asserted. */
#define UART_DMAOnError_Disable	      0x0004  /* DMA receive request disabled
    when the UART error interrupt
    is asserted. */
    /* UART DMA Request */
#define UART_DMAReq_Tx	              0x02      /* Transmit DMA Enable */
#define UART_DMAReq_Rx	              0x01      /* Receive DMA Enable */

    /* UART FLAG */
#define UART_FLAG_OverrunError	      0x23    /* Overrun error flag */
#define UART_FLAG_Break	              0x22    /* break error flag */
#define UART_FLAG_ParityError	      0x21    /* parity error flag */
#define UART_FLAG_FrameError	      0x20    /* frame error flag */
#define UART_FLAG_RI	              0x48    /* RI flag */
#define UART_FLAG_TxFIFOEmpty	      0x47    /* Transmit FIFO Empty flag */
#define UART_FLAG_RxFIFOFull	      0x46    /* Receive FIFO Full flag */
#define UART_FLAG_TxFIFOFull	      0x45    /* Transmit FIFO Full flag */
#define UART_FLAG_RxFIFOEmpty	      0x44    /* Receive FIFO Empty flag */
#define UART_FLAG_Busy	              0x43    /* UART Busy flag */
#define UART_FLAG_DCD	              0x42    /* DCD flag */
#define UART_FLAG_DSR	              0x41    /* DSR flag */
#define UART_FLAG_CTS	              0x40    /* CTS flag */
#define UART_RawIT_OverrunError       0x6A    /* Overrun Error Raw IT flag */
#define UART_RawIT_BreakError         0x69    /* Break Error Raw IT flag */
#define UART_RawIT_ParityError        0x68    /* Parity Error Raw IT flag */
#define UART_RawIT_FrameError         0x67    /* Frame Error Raw IT flag */
#define UART_RawIT_ReceiveTimeOut     0x66    /* ReceiveTimeOut Raw IT flag */
#define UART_RawIT_Transmit	      0x65    /* Transmit Raw IT flag */
#define UART_RawIT_Receive	      0x64    /* Receive Raw IT flag */
#define UART_RawIT_DSR	              0x63    /* DSR Raw IT flag */
#define UART_RawIT_DCD	              0x62    /* DCD Raw IT flag */
#define UART_RawIT_CTS	              0x61    /* CTS Raw IT flag */
#define UART_RawIT_RI	              0x60    /* RI Raw IT flag */

    /*IrDAx select*/
#define IrDA0 0x01                             /*IrDA0 select*/
#define IrDA1 0x02                             /*IrDA0 select*/
#define IrDA2 0x03                             /*IrDA0 select*/

        {

        long long UART_MainClock = 0;
        unsigned int IntegerDivider = 0;
        unsigned int FractionalDivider = 0;

        /* Clear the LCR[6:5] bits */
        /* Choose Stop Bits - One Stop Bits */
        /* Configure the Parity - Clear the LCR[7]and LCR[2:1] bits */
        UART0->LCR &= ( UART_WordLength_Mask & UART_StopBits_1 & UART_Parity_Mask );

        /* Set the LCR[6:5] bits according to UART_WordLength value */
        /* Set the LCR[7]and LCR[2:1] bits according to UART_Parity value */
        UART0->LCR |= ( UART_WordLength_8D | UART_Parity_No );

        /* Configure the BaudRate */
        //UART_MainClock = (SCU_GetMCLKFreqValue())*1000;
        if ((SCU->CLKCNTR&0x3) == 0x2) UART_MainClock = (unsigned int)(__io_Main_Osc);
        else
            {
            if ((SCU->CLKCNTR&0x3) == 0x1) UART_MainClock = (unsigned int)(32000);
            else //UART_MainClock = (SCU_GetPLLFreqValue())*1000;
                {
                unsigned char PLL_M;
                unsigned char PLL_N;
                unsigned char PLL_P;

                PLL_M = SCU->PLLCONF&0xFF;
                PLL_N = (SCU->PLLCONF&0xFF00)>>8;
                PLL_P = (SCU->PLLCONF&0x70000)>>16;

                if ((PLL_M>0)&&(PLL_N>0))
                    UART_MainClock = (unsigned int)(((__io_Main_Osc*2)*PLL_N)/(PLL_M<<PLL_P));

                else UART_MainClock = 0;
                }
            }

        if((SCU->CLKCNTR & 0x200) != 0x200)
            {
            UART_MainClock = UART_MainClock/2;
            }
        /* Determine the integer part */
        IntegerDivider = ((100) * (UART_MainClock) / (16 * (9600)));
        UART0->IBRD = IntegerDivider / 100;

        /* Determine the fractional part */
        FractionalDivider = IntegerDivider - (100 * (UART0->IBRD));
        UART0->FBRD = ((((FractionalDivider * 64) + 50) / 100));

        /* Choose the Hardware Flow Control */
        /* Clear the CR[15:14] bits */
        /* Clear the CR[9:8] bits */
        UART0->CR &= ( UART_HardwareFlowControl_Mask & UART_Mode_Mask );
        /* Set the CR[15:14] bits according to UART_HardwareFlowControl value */
        /* Configure the UART mode - Set the CR[9:8] bits according to UART_Mode value */
        UART0->CR |= ( UART_HardwareFlowControl_None | UART_Mode_Tx_Rx );

        /* Disable the FIFOs */
        UART0->LCR &= UART_FIFO_Disable;
        }


    /* Disable the LoopBack mode of the specified UART */
#define UART_LoopBack_Disable_Mask      0xFF7F	/* LoopBack Disable Mask */
    UART0->CR &= UART_LoopBack_Disable_Mask;

    /* Enable the selected UART by setting the UARTEN bit in the CR register */
#define UART_Enable_Mask	        0x0001	/* UART Enable Mask */
    UART0->CR |= UART_Enable_Mask;

    // IO init done!
    __io_init_done = 1;
    }






/* send the character on UART0. */
void __io_putchar( char c )
    {
    //init UART if needed
    if( !__io_init_done )
        {
        __io_init();
        }

    /* \n is not enough. Need \r too! */
    if( c == 0x0A )
        {
        __io_putchar( 0x0D );
        } 
    while((UART0->FR & 8)!= RESET); // we wait while the UART transmitter is busy

    //UART_SendData(UART0, c);
    UART0->DR = c;

    }

int
putchar (c)
int c;
    {
    __io_putchar( (char) c );
    return c;
    }

int __io_getchar()
    {
    unsigned char  value;
    unsigned short wStatus;

    //init UART if needed
    if( !__io_init_done )
        {
        __io_init();
        }

    while( (UART0->FR & 0x40) == RESET );

    value = ((unsigned char)UART0->DR);

    return (int)(value);
    }


int getchar()
    {
    return __io_getchar();
    }






