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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM