stm32正点原子学习笔记(26)串口寄存器库函数配置方法+手把手教你写串口通信实例
main.c
1 #include "stm32f10x.h" 2 #include"uart.h" 3 4 5 int main(void) 6 { 7 uart_init(115200); 8 while(1) 9 { 10 11 } 12 }
uart.c
1 #include"uart.h" 2 3 void uart_init(u32 bound) 4 { 5 GPIO_InitTypeDef GPIO_InitStructure; 6 NVIC_InitTypeDef NVIC_InitStructure; 7 USART_InitTypeDef USART_InitStructure; 8 9 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_USART1,ENABLE); 10 11 GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; 12 GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9; 13 GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz; 14 15 GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING; 16 GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10; 17 GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz; 18 GPIO_Init(GPIOA,&GPIO_InitStructure); 19 20 USART_InitStructure.USART_BaudRate=bound;//比特率 21 USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;//硬件流 22 USART_InitStructure.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;//发送接收使能 23 USART_InitStructure.USART_Parity=USART_Parity_No;//奇偶校验 24 USART_InitStructure.USART_StopBits=USART_StopBits_1; 25 USART_InitStructure.USART_WordLength=USART_WordLength_8b;//数据位长度(字长) 26 USART_Init(USART1,&USART_InitStructure); 27 28 //使用中断--------------------------- 29 NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//优先级分组在misc.c里,2位抢占,2位响应 30 31 NVIC_InitStructure.NVIC_IRQChannel=USART1_IRQn; 32 NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE; 33 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1; 34 NVIC_InitStructure.NVIC_IRQChannelSubPriority=1; 35 NVIC_Init(&NVIC_InitStructure); 36 37 USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//接收缓冲区非空,即接收中断 38 //---------------------------------- 39 40 USART_Cmd(USART1,ENABLE); 41 } 42 43 void USART1_IRQHandler(void)//中断服务函数,启动文件中找 44 { 45 u8 rec; 46 if(USART_GetITStatus(USART1,USART_IT_RXNE)==SET)//接收中断,状态检测stm32f10x_usart.h中找 47 { 48 rec=USART_ReceiveData(USART1); 49 // if(rec==1) 50 // { 51 USART_SendData(USART1,rec);//(DATA) <= 0x1FF 52 // } 53 } 54 }
uart.h
1 #ifndef __uart_H 2 #define __uart_H 3 4 #include"sys.h" 5 6 void uart_init(u32 bound); 7 8 #endif