117 lines
2.7 KiB
C
117 lines
2.7 KiB
C
#include "usart.h"
|
|
|
|
unsigned char Serial_RxData;
|
|
unsigned char Serial_RxFlag;
|
|
|
|
void Usart_Init(unsigned int BaudRate)
|
|
{
|
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
|
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
|
|
|
|
GPIO_InitTypeDef GPIO_InitStruct;
|
|
GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP;
|
|
GPIO_InitStruct.GPIO_Pin=GPIO_Pin_9;
|
|
GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
|
|
GPIO_Init(GPIOA,&GPIO_InitStruct);
|
|
|
|
GPIO_InitStruct.GPIO_Mode=GPIO_Mode_IPU;
|
|
GPIO_InitStruct.GPIO_Pin=GPIO_Pin_10;
|
|
GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
|
|
GPIO_Init(GPIOA,&GPIO_InitStruct);
|
|
|
|
USART_InitTypeDef USART_InitStruct;
|
|
USART_InitStruct.USART_BaudRate=BaudRate;
|
|
USART_InitStruct.USART_HardwareFlowControl=USART_HardwareFlowControl_None;//不使用流控
|
|
USART_InitStruct.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;//发送接收模式
|
|
USART_InitStruct.USART_Parity=USART_Parity_No;//无校验
|
|
USART_InitStruct.USART_StopBits=USART_StopBits_1;//一位停止位
|
|
USART_InitStruct.USART_WordLength=USART_WordLength_8b;//八位字长
|
|
USART_Init(USART1,&USART_InitStruct);
|
|
|
|
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
|
|
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
|
|
NVIC_InitTypeDef NVIC_InitStruct;
|
|
NVIC_InitStruct.NVIC_IRQChannel=USART1_IRQn;
|
|
NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
|
|
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=1;
|
|
NVIC_InitStruct.NVIC_IRQChannelSubPriority=1;
|
|
NVIC_Init(&NVIC_InitStruct);
|
|
|
|
USART_Cmd(USART1,ENABLE);
|
|
}
|
|
|
|
void Serial_SendByte(unsigned char Byte)
|
|
{
|
|
USART_SendData(USART1,Byte);
|
|
while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==0);
|
|
}
|
|
|
|
void Serial_SendArray(unsigned char *Array,unsigned short Length)
|
|
{
|
|
unsigned short i;
|
|
for(i=0;i<Length;i++)
|
|
{
|
|
Serial_SendByte(Array[i]);
|
|
}
|
|
}
|
|
|
|
void Serial_SendString(char *string)
|
|
{
|
|
unsigned char i;
|
|
for(i=0;string[i]!='\0';i++)
|
|
{
|
|
Serial_SendByte(string[i]);
|
|
}
|
|
|
|
}
|
|
|
|
unsigned int Serial_Pow(unsigned int x,unsigned int y)
|
|
{
|
|
unsigned int Result =1;
|
|
while(y--)
|
|
{
|
|
Result *=x;
|
|
}
|
|
return Result;
|
|
}
|
|
|
|
void Serial_SendNumber(unsigned int Number,unsigned char Length)
|
|
{
|
|
unsigned char i;
|
|
for(i=0;i<Length;i++)
|
|
{
|
|
Serial_SendByte(Number/Serial_Pow(10,Length-i-1)%10+'0');
|
|
}
|
|
}
|
|
|
|
int fputc(int ch,FILE *f)
|
|
{
|
|
Serial_SendByte(ch);
|
|
return ch;
|
|
}
|
|
|
|
unsigned char Serial_GetRxFlag(void)
|
|
{
|
|
if(Serial_RxFlag==1)
|
|
{
|
|
Serial_RxFlag=0;
|
|
return 1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
unsigned char Serial_GetRxData(void)
|
|
{
|
|
return Serial_RxData;
|
|
}
|
|
|
|
void USART1_IRQHandler(void)
|
|
{
|
|
if(USART_GetITStatus(USART1,USART_IT_RXNE)==SET)
|
|
{
|
|
Serial_RxData=USART_ReceiveData(USART1);
|
|
Serial_RxFlag=1;
|
|
USART_ClearITPendingBit(USART1,USART_IT_RXNE);
|
|
}
|
|
}
|