usart.c
#include "usart.h"//USARTÍ·Îļþ
//³õʼ»¯USART2
void USART2_Init(unsigned long ulBaud)
{
//GPIO,USART,ÖжϽṹÌå
GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStruct;
NVIC_InitTypeDef NVIC_InitStruct;
// ÔÊÐíGPIOAºÍUSART2ʱÖÓ
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
// PA2-TX2¸´ÓÃÍÆÍìÊä³ö
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStruct);
// PA3-RX2¸¡¿ÕÊäÈ루¸´Î»×´Ì¬£¬¿ÉÒÔÊ¡ÂÔ£©
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStruct);
// ³õʼ»¯USART2£¨²¨ÌØÂÊulBaud£¬Ä¬ÈÏ8¸öÊý¾Ý룬1¸öֹͣ룬ÎÞУÑ飬ÔÊÐíRxºÍTx£©
USART_InitStruct.USART_BaudRate = ulBaud;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_InitStruct.USART_HardwareFlowControl= USART_HardwareFlowControl_None;//Ó²¼þ¿ØÖÆÁ÷£¬Ò»°ãÑ¡ÔñNone
USART_Init(USART2, &USART_InitStruct);
// ÔÊÐíUSART2
USART_Cmd(USART2, ENABLE);
// ÔÊÐíUSART2½ÓÊÕÖжÏ
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
// ÔÊÐíNVIC USART2ÖжÏ
NVIC_InitStruct.NVIC_IRQChannel = USART2_IRQn;//ÖжÏͨµÀΪUSART2
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;//ÏÈÕ¼ÓÅÏȼ¶
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;//´ÓÓÅÏȼ¶
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;//ÖжÏʹÄÜ
NVIC_Init(&NVIC_InitStruct);//³õʼ»¯
}
// ·¢ËÍ×Ö·û
//Èë¿Ú²ÎÊý·Ö±ðÊÇ£º´®¿ÚÀàÐÍ£¨±ÈÈçUSART2£©£»·¢Ë͵Ä×Ö·û£¨±ÈÈç'A'£©
//·µ»ØÖµÊÇ£º·¢Ë͵Ä×Ö·û£¨±ÈÈç'A'£©
unsigned char USART_SendChar(USART_TypeDef* USARTx, unsigned char ucChar)
{
while(!USART_GetFlagStatus(USARTx, USART_FLAG_TXE));//²»¶Ï¼ì²é±ê־λ
USART_SendData(USARTx, ucChar);//·¢ËÍ×Ö·ûÊý¾Ý
return ucChar;//·µ»Ø·¢Ë͵Ä×Ö·û
}
// ·¢ËÍ×Ö·û´®
//Èë¿Ú²ÎÊý·Ö±ðÊÇ£º´®¿ÚÀàÐÍ£¨±ÈÈçUSART2£©£»·¢Ë͵Ä×Ö·û´®£¨±ÈÈç'dianzijun'£©
void USART_SendString(USART_TypeDef* USARTx, unsigned char* pucStr)
{
while(*pucStr != '\0')//Èç¹û²»µÈÓÚ¡®\0¡¯
USART_SendChar(USARTx, *pucStr++);//·¢ËÍÏÂÒ»¸ö×Ö·û
}