#include "bt.h"

char RxPacket[17];
unsigned char flag;
char open[] = "o";
char close[] = "c";
void uart1_init(u32 bound)
{
    //GPIO端口设置
    GPIO_InitTypeDef GPIO_InitStructure;
	USART_InitTypeDef USART_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//使能UGPIOA时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);//使能USART1时钟

    //USART1_TX  
    GPIO_InitStructure.GPIO_Pin=GPIO_Pin_3;//PA9
    GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;//复用推挽输出
    GPIO_Init(GPIOB,&GPIO_InitStructure);

    //USART1_RX	  
    GPIO_InitStructure.GPIO_Pin=GPIO_Pin_4;//PA10
    GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;//浮空输入
    GPIO_Init(GPIOB,&GPIO_InitStructure);

    //Usart1 NVIC 配置
    NVIC_InitStructure.NVIC_IRQChannel=USART1_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0 ;//抢占优先级
	NVIC_InitStructure.NVIC_IRQChannelSubPriority=1;		//子优先级
	NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;			//IRQ通道使能
	NVIC_Init(&NVIC_InitStructure);	//根据指定的参数初始化VIC寄存器

    //USART 初始化设置
	USART_InitStructure.USART_BaudRate=bound;//串口波特率
	USART_InitStructure.USART_WordLength=USART_WordLength_8b;//字长为8位数据格式
	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);     //初始化串口1
    USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//开启串口接受中断
    USART_ITConfig(USART1,USART_IT_IDLE,ENABLE);
    USART_Cmd(USART1,ENABLE);                    //使能串口1 
}

void BT_Send(char *string)
{
    flag=0;
    printf("%s",string);
    while(flag==0);
}

void BT_Init(void)
{
    uart1_init(115200);
    BT_Send("AT+BAUD8");
    BT_Send("AT");
    BT_Send("AT+VERSION");
    BT_Send("AT+NAMEJOJO");
    BT_Send("AT+PIN1234");
    OLED_ShowString(3,1,"OK");
}
int BT_Judge(void)
{
	if(strcmp(RxPacket,open))
		return 1;
	else
		return 0;
}
/**************************************************************************
Function: Receive interrupt function
Input   : none
Output  : none
函数功能：串口1接收中断
入口参数：无
返回  值：无
**************************************************************************/
void USART1_IRQHandler(void)
{
    static unsigned char i=0;
    unsigned char clear;
    if(USART_GetITStatus(USART1,USART_IT_RXNE)!=RESET)
    {
        RxPacket[i++]=USART_ReceiveData(USART1);
        USART_ClearITPendingBit(USART1,USART_IT_RXNE);
    }
    else if((USART_GetITStatus(USART1,USART_IT_IDLE)!=RESET))
    {
        RxPacket[16]=0x00;
        OLED_ShowString(2,1,RxPacket);
        i=0;
        memset(RxPacket,' ',17);
        clear=USART1->SR;
        clear=USART1->DR;
        flag=1;
    }
}

int fputc(int ch,FILE *f)
{
	while((USART1->SR&0X40)==0);
    USART1->DR=(unsigned char)ch;
	return ch;
}
