/*******************************************************************************
 * Copyright (c) 2018 Renesas Electronics Corporation. All rights reserved.
 *
 * DESCRIPTION   : SCIF driver
 ******************************************************************************/

#include <stdint.h>
#include <stdio.h>
#include <scif_register.h>
#include <rcar_def.h>
#include <scif.h>
#include <mem_io.h>

void scif_init(void)
{
	volatile uint16_t reg;
	
	mem_write16(SCIF_SCSMRIR, 0x0000U);	/* SCIF channel0 as SCIF	*/

	reg = mem_read16(SCIF_SCLSR);		/* dummy read     		*/
	mem_write16(SCIF_SCLSR, 0x0000U);	/* clear ORER bit 		*/
	mem_write16(SCIF_SCFSR, 0x0000U);	/* clear all error bit	*/

	mem_write16(SCIF_SCSCR, 0x0000U);	/* clear SCR.TE & SCR.RE*/
	mem_write16(SCIF_SCFCR, 0x0006U);	/* reset tx-fifo, reset rx-fifo. */

	mem_write16(SCIF_SCSCR, 0x0000U);	/* internal clock, SC_CLK pin unused for output pin */
	mem_write16(SCIF_SCSMR, 0x0000U);	/* 8bit data, no-parity, 1 stop, Po/1 */
//	micro_wait(10U); /* 10us */
	mem_write16(SCIF_SCBRR, 0x11U);		/* Pclk(66MHz)/1, 115.2kBps*/
						/* N = 66/(66/2*115200)*10^4-1 =17=> 0x11 */
//	micro_wait(10U); /* 10us */
	mem_write16(SCIF_SCFCR, 0x0000U);	/* reset-off tx-fifo, rx-fifo. */
	mem_write16(SCIF_SCSCR, 0x0030U);	/* enable TE, RE; SC_CLK=no output */
//	micro_wait(10U); /* 10us */
}

void console_puts(char *str,char rtn)
{
	while (*str) {
		console_putc(*str);
		str++;
	}

	if(rtn == 1){
		console_putc(CR_CODE);
		console_putc(LF_CODE);
	}
}

void console_putc(uint8_t outchar)
{
	uint16_t reg;

	while (!(0x60U & mem_read16(SCIF_SCFSR))) {
	}

	mem_write8(SCIF_SCFTDR, outchar);
	reg = mem_read16(SCIF_SCFSR);
	reg &= ~0x60U; /* TEND,TDFE clear */
	mem_write16(SCIF_SCFSR, reg);
}
