void USART_Configuration(void)//串口初始化函数
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_AHBPeriphClockCmd( RCC_AHBPeriph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE );
GPIO_PinAFConfig(GPIOA,GPIO_PinSource14,GPIO_AF_1);
GPIO_PinAFConfig(GPIOA,GPIO_PinSource15,GPIO_AF_1);
/*
* USART1_TX -> PA14 , USART1_RX -> PA15
*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14|GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
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;//设置工作模式
USART_Init(USART2, &USART_InitStructure); //配置入结构体
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPriority = 2;
NVIC_Init(&NVIC_InitStructure);
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
USART_Cmd(USART2, ENABLE);//使能串口1
}void UART_send_byte(uint8_t byte) //发送1字节数据
{
while(!((USART2->ISR)&(1<<7)));
USART2->TDR=byte;
}
void UART_Send(uint8_t *Buffer, uint32_t Length)
{
while(Length != 0)
{
while(!((USART2->ISR)&(1<<7)));//等待发送完
USART2->TDR= *Buffer;
Buffer++;
Length--;
}
}
void UART_Rec(uint8_t *Buffer, uint32_t Length)
{
if(USART2->ISR & (1<<5))
{
while(Length !=0)
{
while(!(USART2->ISR & (1<<5)));
*Buffer = USART2->RDR;
Buffer++;
Length--;
}
}
}
uint8_t UART_Recive(void)
{
while(!(USART2->ISR & (1<<5)));//等待接收到数据
return(USART2->RDR); //读出数据
}
PUTCHAR_PROTOTYPE
{
/* 将Printf内容发往串口 */
USART_SendData(USART2,(uint8_t) ch);
while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET)
{}
return (ch);
}void USART2_IRQHandler(void)
{
if(USART2->ISR & (1<<5))
{
//USART_ClearITPendingBit(USART1, USART_IT_RXNE);
code[cnum] = USART2->RDR;
cnum++;
if(cnum >= 4)
{
cnum = 0;
cflg = 1;
}
}
}