#include <stm32f10x_usart.h>
#include <stm32f10x_tim.h>
#include "usart.h"
#include "rcc.h"
#include "global.h"

void SendMode_485(void)      
{
	GPIO_SetBits(GPIOB,GPIO_Pin_12);
	delayus(3);
}

void ReceiveMode_485(USART_TypeDef* USARTx)   
{
	while (USART_GetFlagStatus(USARTx, USART_FLAG_TC) == RESET){};
	GPIO_ResetBits(GPIOB,GPIO_Pin_12);
	delayus(3);
}

void USARTSendString(USART_TypeDef* USARTx, u8 *data, u8 len)
{	
	u8 i;

	SendMode_485();
	for(i = 0; i < len; i++)
	{
		//Send out one byte
		USART_SendData(USARTx, data[i]);
		/* Loop until the end of transmission */
  		while (USART_GetFlagStatus(USARTx, USART_FLAG_TC) == RESET)
  		{
  		}
	}
	ReceiveMode_485(USARTx);
}

void USARTInit(USART_TypeDef* USARTx, u32 baudRate)
{
	USART_InitTypeDef USART_InitStructure;
	/* USARTx configured as follow:
        - BaudRate = 9600 baud  
        - Word Length = 8 Bits
        - One Stop Bit
        - No parity
        - Hardware flow control disabled (RTS and CTS signals)
        - Receive and transmit enabled
  	*/

  	if(baudRate == 0x00){//2400
		USART_InitStructure.USART_BaudRate = 2400;
	}else if(baudRate == 0x01){//4800
		USART_InitStructure.USART_BaudRate = 4800;
	}else if(baudRate == 0x03){//19200
		USART_InitStructure.USART_BaudRate = 19200;										  //串口初始化定义
	}else if(baudRate == 0x04){//115200
		USART_InitStructure.USART_BaudRate = 115200;										  //串口初始化定义
	}else if(baudRate == 0x05){//38400
		USART_InitStructure.USART_BaudRate = 38400;										  
	}else if(baudRate == 0x06){//57600
		USART_InitStructure.USART_BaudRate = 57600;										  
	}else if(baudRate == 0x07){//14400
		USART_InitStructure.USART_BaudRate = 14400;										 
	}else {
		USART_InitStructure.USART_BaudRate = 9600;
	}
  	USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  	USART_InitStructure.USART_StopBits = USART_StopBits_1;
  	USART_InitStructure.USART_Parity = USART_Parity_No;
  	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  	USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  
  	/* Configure USARTy */
  	USART_Init(USARTx, &USART_InitStructure);

	/* Enable the USARTy */
  	USART_Cmd(USARTx, ENABLE);
}

