/*
 * Copyright (c) 2018 Renesas Electronics Corporation. All rights reserved.
 */

#include "common.h"
#include "scifdrv0.h"
#include "bit.h"
#include "reg_rcargen3.h"


//////////////////////////////////////////////////////////////////////////////////
//                                                                              //
//	Debug Seirial(SCIF0)														//
//																				//
//////////////////////////////////////////////////////////////////////////////////
int32_t PutCharSCIF0(char outChar)
{
	while(!(0x60 & *((volatile uint16_t*)SCIF0_SCFSR) ));
	*((volatile uint8_t*)SCIF0_SCFTDR) = outChar;
	*((volatile uint16_t*)SCIF0_SCFSR) &= ~0x60;	/* TEND,TDFE clear */
	return(0);
}

void PowerOnScif0(void)
{
	uint32_t dataL;

	dataL = *((volatile uint32_t*)CPG_MSTPSR2);
	if(dataL & BIT7){	// case SCIF0
		dataL &= ~BIT7;
		*((volatile uint32_t*)CPG_CPGWPR)    = ~dataL;
		*((volatile uint32_t*)CPG_SMSTPCR2)  =  dataL;
		while( BIT7 & *((volatile uint32_t*)CPG_MSTPSR2) );  // wait bit=0
	}
}

void WaitPutScif0SendEnd(void)
{
	uint16_t dataW;
    uint32_t loop;

	loop=1;
    while(loop){
		dataW = *((volatile uint16_t*)SCIF0_SCFSR);
		if(dataW & BIT6)	loop = 0;
	}
}

void InitScif0PinFunction(void)
{
	uint32_t dataL;

	/* SCIF0 */
	dataL = *((volatile uint32_t*)PFC_IPSR7);
        dataL &= ~(0x0FF00000);
 	dataL |= 0x04400000;				/* IPSR7[27:24]=4'b0100, IPSR7[23:20]=4'b0100 */
	*((volatile uint32_t*)PFC_PMMR) = ~dataL;
	*((volatile uint32_t*)PFC_IPSR7) = dataL;

	dataL = *((volatile uint32_t*)PFC_GPSR4);
	dataL |= 0x00000030;				/* GPSR4[5],GPSR4[4] */
	*((volatile uint32_t*)PFC_PMMR) = ~dataL;
	*((volatile uint32_t*)PFC_GPSR4) = dataL;
}

void InitScif0_SCIFCLK(void)
{
	uint16_t dataW;

	PowerOnScif0();

	InitScif0PinFunction();

	dataW = *((volatile uint16_t*)SCIF0_SCLSR);	/* dummy read     		*/
	*((volatile uint16_t*)SCIF0_SCLSR) = 0x0000;	/* clear ORER bit 		*/
	*((volatile uint16_t*)SCIF0_SCFSR) = 0x0000;	/* clear all error bit	*/

	*((volatile uint16_t*)SCIF0_SCSCR) = 0x0000;	/* clear SCR.TE & SCR.RE*/
	*((volatile uint16_t*)SCIF0_SCFCR) = 0x0006;	/* reset tx-fifo, reset rx-fifo. */
	*((volatile uint16_t*)SCIF0_SCFSR) = 0x0000;	/* clear ER, TEND, TDFE, BRK, RDF, DR */

	*((volatile uint16_t*)SCIF0_SCSCR) = 0x0000;	/* internal clock, SC_CLK pin used for input pin */
	*((volatile uint16_t*)SCIF0_SCSMR) = 0x0000;	/* 8bit data, no-parity, 1 stop, Po/1 */
	SoftDelay(100);
	*((volatile uint8_t*)SCIF0_SCBRR)  = 0x11;	/* 115200bps@66MHz */
	SoftDelay(100);
	*((volatile uint16_t*)SCIF0_SCFCR) = 0x0000;	/* reset-off tx-fifo, rx-fifo. */
	*((volatile uint16_t*)SCIF0_SCSCR) = 0x0030;	/* enable TE, RE; SC_CLK=input */

	SoftDelay(100);
}
