stm32串口是实现单片机到上位机通讯的重要手段,通常使用usb转ttl模块进行单片机与上位机的连接,以实现串口的收发等功能。今天学习了串口的发送与中断接收,现总结如下:
步骤总结:
配置两个GPIO分别为RX、TX->配置串口结构体->(请空标志位)->开启定时器中断->使能定时器中断->配置NVIC结构体->编写中断服务函数->编写相关实现程序
UART.h:
#include "UART.h"#include "stm32f10x.h"#include "stdio.h"void UART_Config(void){//开时钟RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);//定义结构体变量GPIO_InitTypeDef GPIOInitStructure;USART_InitTypeDef UARTInitStructure;NVIC_InitTypeDef NVICInitStructure;//配置PA9 TXGPIOInitStructure.GPIO_Pin = GPIO_Pin_9;GPIOInitStructure.GPIO_Mode = GPIO_Mode_AF_PP;GPIOInitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOA, &GPIOInitStructure);//配置PA10 RXGPIOInitStructure.GPIO_Pin = GPIO_Pin_10;GPIOInitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;GPIOInitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOA, &GPIOInitStructure);//配置串口结构体UARTInitStructure.USART_BaudRate = 115200;UARTInitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;UARTInitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;UARTInitStructure.USART_Parity = USART_Parity_No;UARTInitStructure.USART_StopBits = USART_StopBits_1;UARTInitStructure.USART_WordLength = USART_WordLength_8b;USART_Init(USART1, &UARTInitStructure);//清空标志位USART_ClearFlag(USART1,USART_FLAG_RXNE);//开启定时器中断USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//使能定时器USART_Cmd(USART1,ENABLE);//配置NVIC结构体NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);NVICInitStructure.NVIC_IRQChannel = USART1_IRQn;NVICInitStructure.NVIC_IRQChannelPreemptionPriority = 3;NVICInitStructure.NVIC_IRQChannelSubPriority = 3;NVICInitStructure.NVIC_IRQChannelCmd = ENABLE;NVIC_Init(&NVICInitStructure);}//发送字节void USART_SendByte(USART_TypeDef* USARTx, uint16_t Data){USART_SendData(USARTx,Data);while(USART_GetFlagStatus(USARTx, USART_FLAG_TXE) == RESET);}//发送字符串void USART_SendStr(USART_TypeDef* USARTx, char *str){uint16_t i = 0;do{USART_SendByte(USARTx, *(str + i));i++;}while(*(str + i) !='');while(USART_GetFlagStatus(USARTx, USART_FLAG_TC) == RESET);}//重定向printfint fputc(int ch, FILE *f){USART_SendData(USART1,(uint8_t) ch);while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);return (ch);}//重定向putcharint fgetc(FILE *f){while(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET);return (int)USART_ReceiveData(USART1);}
stm32f10x_it.c:
void USART1_IRQHandler(void){char temp;if(USART_GetITStatus(USART1, USART_IT_RXNE ) != RESET){temp = USART_ReceiveData(USART1);if(temp == 'O'){GPIO_ResetBits( LED_G_GPIO_PORT, LED_G_GPIO_PIN);USART_SendStr(USART1,"led is ON");}if(temp == 'C'){GPIO_SetBits( LED_G_GPIO_PORT, LED_G_GPIO_PIN);USART_SendStr(USART1,"led is OFF");}}USART_ClearITPendingBit(USART1,USART_IT_RXNE);//一定要注意清空标志位!}
main.c:
#include "stm32f10x.h"#include "UART.h"#include "stdio.h"#include "led.h"int main(void){UART_Config();LED_GPIO_Confing();GPIO_SetBits(LED_G_GPIO_PORT, LED_G_GPIO_PIN);while(1){}}
接收实验功能为:通过串口助手发送O,则点亮LED,发送C,LED熄灭。