#include "debug.h"
#include "ioctrl_drv.h"

static UART_TypeDef *UART;

////////////////////////////////////////////////////////////////////////////////// 	 

//-------------------------------------------------------------------
//加入以下代码,支持printf函数,而不需要选择use MicroLIB	 
#pragma import(__use_no_semihosting)          
//解决HAL库使用时,某些情况可能报错的bug
int _ttywrch(int ch)    
{
	ch=ch;
	return ch;
}
//标准库需要的支持函数                 
struct __FILE 
{ 
	int handle; 
	/* Whatever you require here. If the only file you are using is */ 
	/* standard output using printf() for debugging, no file handling */ 
	/* is required. */ 
}; 
/* FILE is typedef’ d in stdio.h. */ 
FILE __stdout;       
//定义_sys_exit()以避免使用半主机模式    
void _sys_exit(int x) 
{ 
	x = x; 
} 

#if Uart_debug                                                                                                                                              
	//重定义fputc函数 
	int fputc(int ch, FILE *f)
	{ 
		UART_TypeDef *UARTx = SCI1;
		
		UARTx->SCICR2|= SCICR2_TE_MASK;
		
		while( (UARTx->SCISR1&SCISR1_TDRE_MASK)==0x00 ) { ; }		
		UARTx->SCIDRL=(UINT8)ch;
		while( (UARTx->SCISR1&SCISR1_TC_MASK)==0x00 ) { ; }	
	
		UARTx->SCICR2&= ~SCICR2_TE_MASK;
		
		return ch;
	}           
#else   
	//重定义fputc函数 
	int fputc(int ch, FILE *f)
	{      
	
		UART->SCIDRL =(UINT8)ch;
		while ((UART->SCISR1 & 0x40) == 0x00){};
		
		return ch;
	}
#endif       

//end
//-----------------------------------------------------------------		

//pclk:PCLK时钟频率(Mhz)
//bound:波特率 
void UARTDebugPort_Init(UART_TypeDef *UARTx,UINT32 baudrate)
{  	 
	UINT32 band_rate=0;
	
	UART = UARTx;

	IO_Ctrl_SCI_Swap(TX1_GINT4,TRUE);                                  //OPEN TX1 RX1 function
	IO_Ctrl_SCI_Swap(RX1_GINT0,TRUE);
	
	UART->SCIBRDF=(((g_ips_clk*8/baudrate)+1)/2)&0x003f;
	band_rate =(g_ips_clk*4/baudrate)>>6;
	UART->SCIBDH=(UINT8)((band_rate>>8)&0x00ff);
	UART->SCIBDL=(UINT8)(band_rate&0x00ff);
	
	UART->SCICR1=0x00;
	UARTx->SCICR2 = SCICR2_TE_MASK;
}

void assert_failed(UINT8* file, UINT32 line)
{
	printf("Wrong parameters value: file %s on line %d\r\n", file, line);
	while(1);
}













