#include "sys.h"
#include "usart.h"
#include "delay.h"
//////////////////////////////////////////////////////////////////////////////////	 
//本程序只供学习使用，未经作者许可，不得用于其它任何用途
//ALIENTEK Mini STM32开发板
//串口1初始化		   
//正点原子@ALIENTEK
//技术论坛:www.openedv.com
//修改日期:2010/5/27
//版本：V1.3
//版权所有，盗版必究。
//Copyright(C) 正点原子 2009-2019
//All rights reserved
//********************************************************************************
//V1.3修改说明 
//支持适应不同频率下的串口波特率设置.
//加入了对printf的支持
//增加了串口接收命令功能.
//修正了printf第一个字符丢失的bug
////////////////////////////////////////////////////////////////////////////////// 	  


//加入以下代码,支持printf函数,而不需要选择use MicroLIB
#if 1
#pragma import(__use_no_semihosting)             
//标准库需要的支持函数                 
struct __FILE 
{ 
	int handle; 

}; 

FILE __stdout;       
//定义_sys_exit()以避免使用半主机模式    
_sys_exit(int x) 
{ 
	x = x; 
} 
//重定义fputc函数 
int fputc(int ch, FILE *f)
{      
	while((USART1->SR&0X40)==0);//循环发送,直到发送完毕   
    USART1->DR = (u8) ch;      
	return ch;
}
#endif 

/*使用microLib的方法*/
 /* 
int fputc(int ch, FILE *f)
{
	USART_SendData(USART1, (uint8_t) ch);

	while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET) {}	
   
    return ch;
}
int GetKey (void)  { 

    while (!(USART1->SR & USART_FLAG_RXNE));

    return ((int)(USART1->DR & 0x1FF));
}
*/
 
// u8 USART_RX_BUF[64];     //接收缓冲,最大64个字节.
//接收状态
//bit7，接收完成标志
//bit6，接收到0x0d
//bit5~0，接收到的有效字节数目
u8 USART_RX_STA=0;       //接收状态标记

void uart_init(u32 bound){
    //GPIO端口设置
    GPIO_InitTypeDef GPIO_InitStructure;
	USART_InitTypeDef USART_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;
	 
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA|RCC_APB2Periph_AFIO|RCC_APB2Periph_GPIOB, ENABLE);
		RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);  
	
	
	
     //USART1_TX   PA.9
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
   
    //USART1_RX	  PA.10
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOA, &GPIO_InitStructure);  

	//	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);   //使能PB端口时钟
		GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;	    		 //PD.12 端口配置
		GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; 		 //推挽输出
		GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; 
		GPIO_Init(GPIOB, &GPIO_InitStructure);	
		GPIO_ResetBits(GPIOB,GPIO_Pin_12); 						 //PB.2 输出低
	
	
        /* Configure USART3 Rx as input floating */
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
        GPIO_Init(GPIOB, &GPIO_InitStructure);

		/* Configure USART3 Tx as alternate function push-pull */
		GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
		GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
		GPIO_Init(GPIOB, &GPIO_InitStructure);	
	
	
   //Usart1 NVIC 配置

  NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;		//

	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;			//IRQ通道使能
	NVIC_Init(&NVIC_InitStructure);	//根据NVIC_InitStruct中指定的参数初始化外设NVIC寄存器USART1
  
   //USART 初始化设置
   
	USART_InitStructure.USART_BaudRate = bound;//一般设置为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;

    USART_Init(USART1, &USART_InitStructure);
   

//     USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//开启中断
   
    USART_Cmd(USART1, ENABLE);                    //使能串口 
		
		
		
   //Usart3 NVIC 配置

  NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;		//
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;			//IRQ通道使能
	NVIC_Init(&NVIC_InitStructure);	//根据NVIC_InitStruct中指定的参数初始化外设NVIC寄存器USART1
  
   //USART 初始化设置
   
	USART_InitStructure.USART_BaudRate = bound;//一般设置为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;

    USART_Init(USART3, &USART_InitStructure);
   

    USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);//开启中断
   
    USART_Cmd(USART3, ENABLE);                    //使能串口 		
}





u8 newCmd = 0;//接收标志位
u8 dataIn[15] = {0}; //存储接收到的数据
u8 Addr;//存储传感器地址


enum RdSerialState {
	SeekForHead,		//字头
	ReadLength,			//字长
	ReadAddr,				//地址
	ReadData,				//读数据
	ReadRange,			//读功能码
	ReadChecksum		//读校验位
};

/*
函数作用：解析收到的数据
输入：uartIn  接收到的数据
输出：addr  地址
输出：dataOut 接收到的角度数据
*/
u8 ReadSerial(u8 uartIn, u8* addr,u8* dataOut)
{
	static u8 checksum = 0;
	static enum RdSerialState rdSerialState = SeekForHead;
	static u8 length = 0;
	static u8 dataArrIndex = 0;
	int i;
	u8 newCmd = 0;

	switch(rdSerialState) {
		case SeekForHead: {
			if(0x77==uartIn) {
				rdSerialState = ReadLength;
			}
			checksum = 0;
			dataArrIndex = 0;
			break;
		}		
	case ReadLength: {
			checksum = checksum+uartIn;
			rdSerialState = ReadAddr;
			length = uartIn-1;
			break;
		}
		case ReadAddr: {
			checksum = checksum+uartIn;
			*addr = uartIn;
			rdSerialState = ReadRange;
			length--;
			break;
		}
		case ReadRange: {
			checksum = checksum+uartIn;
			length--;	
			if(0x84==uartIn) {
				rdSerialState = ReadData;
				for(i = 1; i<10; i++) 
				{
					dataOut[i] = 0;
				}
			}
			else rdSerialState = SeekForHead;
			
			break;
		}
		case ReadData: {
			checksum = checksum+uartIn;
			
			length--;
			if(1==length) {
				rdSerialState = ReadChecksum;
			}else {
				rdSerialState = ReadData;
			}
			if(dataArrIndex>=15) {
				rdSerialState = SeekForHead; 
			}else {
				dataOut[dataArrIndex] = uartIn;
				dataArrIndex++;
			}
			
			break;	
		}
	
		case ReadChecksum: {
			rdSerialState = SeekForHead;
			if((checksum==uartIn) && (length == 1)) {	   //Be sure the command is for the sensor of the right addr
				newCmd = 1;
			}
			break;
		}
	}

	return newCmd;
}



// void USART1_IRQHandler(void)
// { 
// 	u8 data;
// 	
//   if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
//   {
//     	/* Read one byte from the receive data register */
//     	data = USART_ReceiveData(USART1);

// 			newCmd = ReadSerial(data,&Addr,dataIn); 
// 	}
// }

//USART3接收中断
void USART3_IRQHandler(void)
{ 
	u8 data;
	
  	if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET)
  	{
    	/* Read one byte from the receive data register */
    	data = USART_ReceiveData(USART3);
		//put the data to fifo, the readSerial() will get data from fifo at proper time
			newCmd = ReadSerial(data,&Addr,dataIn);     
	}
}

void USART1_Send_Byte(u8 byte)   //串口发送一个字节
{
	GPIO_SetBits(GPIOB,GPIO_Pin_12);		//输出允许
	delay_ms(5);
  USART_SendData(USART1, byte);        //通过库函数  发送数据
  while( USART_GetFlagStatus(USART1,USART_FLAG_TC)!= SET);  
        //等待发送完成。   检测 USART_FLAG_TC 是否置1；    //见库函数 P359 介绍
	GPIO_ResetBits(GPIOB,GPIO_Pin_12);	//接收允许
}

/*------------串口1 发送一个字符串-------------------
程序调用示例：
uchar code str1[]="XiaoQiang";  //定义一个 字符串  注意 字符串 是"" 
UART1_Send_Str(str1);         //发送字符串
-----------------------------------------------------*/
//发送字符串 函数   应用指针 方法
void UART1_Send_Str(unsigned char *s)//发送字符串 函数   应用指针 方法
{
        unsigned char i=0;  //定义一个局部变量  用来 发送字符串 ++运算

        while(s[i]!='\0')  // 每个字符串结尾 都是以  \0 结尾的
        {
                USART_SendData(USART1,s[i]);        //通过库函数  发送数据
                while( USART_GetFlagStatus(USART1,USART_FLAG_TC)!= SET);  
                //等待发送完成。   检测 USART_FLAG_TC 是否置1；    //见库函数 P359 介绍

                i++;                 //i++一次
        }

}
