/*
 * comm_printf.c
 *
 *  Created on: 2023年3月28日
 *      Author: User
 */


#include "comm_printf.h"


 void sci_gpioMux(void)
{
/*
 * pin14 config as SCIB_TX AND PIN15 connfig as SCIB_RX
 */
     GPIO_SetupPinMux(15, GPIO_MUX_CPU1, 2);
     GPIO_SetupPinOptions(15, GPIO_INPUT, GPIO_PUSHPULL);
     GPIO_SetupPinMux(14, GPIO_MUX_CPU1, 2);
     GPIO_SetupPinOptions(14, GPIO_OUTPUT, GPIO_ASYNC);

}


 void printf_sciFifoInit(volatile struct SCI_REGS* sciRegs)
{
    ASSERT(sciRegs != NULL);

    ScibRegs.SCIFFTX.all = 0xE040;
    ScibRegs.SCIFFRX.all = 0x2044;
    ScibRegs.SCIFFCT.all = 0x0;
}

 void printf_sciConfig(volatile struct SCI_REGS* sciRegs)
{
    ASSERT(sciRegs != NULL);

    /*sciRegs->SCICCR.all = 0x0007;//8 char bits
    sciRegs->SCICTL1.all = 0x0003;//
    sciRegs->SCICTL2.all = 0x0003;
    sciRegs->SCICTL2.bit.TXINTENA = 1;
    sciRegs->SCICTL2.bit.RXBKINTENA = 1;

    ScibRegs.SCIHBAUD.all = 0x0002;
    ScibRegs.SCILBAUD.all = 0x008B;

    sciRegs->SCICTL1.all = 0x0023;//relinquish SCI from reset
    */
       ScibRegs.SCICCR.all = 0x0007;   // 1 stop bit,  No loopback
                                       // No parity,8 char bits,
                                       // async mode, idle-line protocol
       ScibRegs.SCICTL1.all = 0x0003;  // enable TX, RX, internal SCICLK,
                                       // Disable RX ERR, SLEEP, TXWAKE
       ScibRegs.SCICTL2.all = 0x0003;
       ScibRegs.SCICTL2.bit.TXINTENA = 1;
       ScibRegs.SCICTL2.bit.RXBKINTENA = 1;

       //
       // SCIB at 9600 baud
       // @LSPCLK = 50 MHz (200 MHz SYSCLK) HBAUD = 0x02 and LBAUD = 0x8B.
       // @LSPCLK = 30 MHz (120 MHz SYSCLK) HBAUD = 0x01 and LBAUD = 0x86.
       //
       ScibRegs.SCIHBAUD.all = 0x0002;
       ScibRegs.SCILBAUD.all = 0x008B;

       ScibRegs.SCICTL1.all = 0x0023;  // Relinquish SCI from Reset



}


void comm_printfInit(volatile struct SCI_REGS* sciRegs)
{
    //sci_gpioMux();
    printf_sciFifoInit(sciRegs);
    printf_sciConfig(sciRegs);

}

#define MAX_WRITE_LEN (128)
void uart_printf(char * fmt, ...)
{
    char *  arg_ptr;
    unsigned int  i ,  len;
    static char write_buf[MAX_WRITE_LEN];

    va_start(arg_ptr, fmt);
    len = vsprintf((char *)write_buf, fmt, arg_ptr);
    va_end(arg_ptr);

    for (i = 0; i < len; i++)
    {
        if ( '\0' != write_buf[i] )
        {
            while (ScibRegs.SCIFFTX.bit.TXFFST != 0);
            ScibRegs.SCITXBUF.all=write_buf[i];
        }
    }
}


//
// scib_xmit - Transmit a character from the SCI
//传输单个字符
void scib_xmit(int a)
{
    while (ScibRegs.SCIFFTX.bit.TXFFST != 0) {}
    ScibRegs.SCITXBUF.all =a;
}

//
// scib_msg - Transmit message via SCIB
//
void scib_msg(char * msg)
{
    int i;
    i = 0;
    while(msg[i] != '\0')
    {
        scib_xmit(msg[i]);
        i++;
    }
}


int fputc(int ch,FILE *f)
{
    #ifdef PRINTF_SCIB
    #if 0

    while(ScibRegs.SCIFFTX.bit.TXFFST != 0);
    ScibRegs.SCITXBUF.all = ch;

    #endif
    #endif
    return ch;
}
