2021-11-17 09:20:49
使能串口时钟和GPIO时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //使能GPIO时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE); //使能AFIO时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); //使能串口时钟
配置GPIO(TX、RX)
GPIO_InitTypeDef gpioinitstructure;
// 配置PA9 TX
gpioinitstructure.GPIO_Mode = GPIO_Mode_AF_PP;
gpioinitstructure.GPIO_Pin = GPIO_Pin_9;
gpioinitstructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init( GPIOA, &gpioinitstructure);
// 配置PA10 RX
gpioinitstructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
gpioinitstructure.GPIO_Pin = GPIO_Pin_10;
GPIO_Init( GPIOA, &gpioinitstructure);
配置串口
USART_InitTypeDef usartinitsturure;
usartinitsturure.USART_BaudRate = 115200;
usartinitsturure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
usartinitsturure.USART_Mode = USART_Mode_Rx |USART_Mode_Tx;
usartinitsturure.USART_Parity =USART_Parity_No;
usartinitsturure.USART_StopBits = USART_StopBits_1;
usartinitsturure.USART_WordLength = USART_WordLength_8b;
USART_Init(USART1, &usartinitsturure);
USART_ITConfig(USART1, USART_IT_RXNE,ENABLE);//串口中断配置,第二个参数是表示使能串口的类型,也就是使能哪种中断,因为串口的中断类型有很多种。
USART_Cmd(USART1, ENABLE);//使能串口
开启中断,初始化NVIC
NVIC_InitTypeDef NVICinitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2 );
NVICinitStructure.NVIC_IRQChannel = USART1_IRQn;
NVICinitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVICinitStructure.NVIC_IRQChannelSubPriority = 1;
NVICinitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVICinitStructure);
串口中断处理函数
void USART1_IRQHandler(void)
{
char tmp;
if(USART_GetITStatus(USART1, USART_IT_RXNE) !=RESET )
{
tmp = USART_ReceiveData(USART1);
if(tmp == 'o')
{
GPIO_ResetBits(GPIOA, GPIO_Pin_1);
USARTSendStr(USART1,"led is opened ");
}
if(tmp == 'c')
{
GPIO_SetBits(GPIOA, GPIO_Pin_1);
USARTSendStr(USART1,"led is closed ");
}
}
}
补充:串口发送字符、发送字符串、重定向printf、重定向scanf
串口发送字符
void USARTSendByte(USART_TypeDef* USARTx, uint16_t Data)
{
USART_SendData(USARTx, Data);
while( USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
发送字符串
void USARTSendStr(USART_TypeDef* USARTx,char *str)
{
uint16_t i = 0;
do
{
USARTSendByte(USART1, *(str +i));
i++;
}while(*(str +i) != '