2019年11月10日

1:对STM32中文数据手册解读之后,相信大家对USART串行通信有些了解,学习51的时候也都接触过,使用串口只要弄明白原理就很简单了

发送和接收数据的过程从图上可以直观的看出

USART串口通信涉及到几个重要的寄存器

 1:)状态寄存器

2)数据寄存器

 

3)波特比率寄存器

 

例:若要设置比特率为9600,那么DIV就是468.75,则此寄存器的高12位应存值:468,低4位存值:0.75*16=12(十进制小数换算成十六进制小数);最后将整数和小数拼接:BRR=468<<4+12;(详细过程可参照源代码;)

4)控制寄存器1:

5)控制寄存器2:

主要配置停止位,时钟极性,时钟使能

6)控制寄存器3:

 涉及到硬件流控制,DMA配置等

发送数据:

接收数据:

相关程序:

中断函数:

void USART1_IRQHandler(void)

 {

        static u8 ch; 

        USART_ClearFlag(USART1 , USART_FLAG_TC);  

if(USART_GetITStatus(USART1, USART_IT_RXNE) != Bit_RESET)

{

       ch=USART_ReceiveData(USART1);

            while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == Bit_RESET);                                                        USART_SendData(USART1, ch);     

            while(USART_GetFlagStatus(USART1, USART_FLAG_TC));   

}

 }

主程序:

int main()

{

 usart_init();

  while(1);

}

配置程序:

void usart_init()

{

  GPIO_InitTypeDef  GPIO_InitStructure;

  USART_InitTypeDef USART_InitStructure;

  NVIC_InitTypeDef NVIC_InitStructure;

  USART_DeInit(USART1);

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOC|RCC_APB2Periph_AFIO|RCC_APB2Periph_USART1,ENABLE);  

 GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;          

GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;

GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;  

GPIO_Init(GPIOA,&GPIO_InitStructure); 

 GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;         

GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;

GPIO_Init(GPIOA,&GPIO_InitStructure);

USART_InitStructure.USART_BaudRate = 9600;           

USART_InitStructure.USART_WordLength = USART_WordLength_8b;

USART_InitStructure.USART_StopBits = USART_StopBits_1;    

USART_InitStructure.USART_Parity = USART_Parity_No;        

USART_InitStructure.USART_HardwareFlowControl =

USART_HardwareFlowControl_None;                        

USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;

USART_Init(USART1, &USART_InitStructure);

USART_Cmd(USART1, ENABLE);    

USART_ITConfig (USART1,USART_IT_RXNE,ENABLE);   

USART_ClearFlag(USART1,USART_FLAG_TC);

NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0); 

 NVIC_InitStructure.NVIC_IRQChannel=USART1_IRQn;

 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1;

 NVIC_InitStructure.NVIC_IRQChannelSubPriority=0;

 NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;

 NVIC_Init(&NVIC_InitStructure); 

}

猜你喜欢

转载自www.cnblogs.com/dpc666/p/11831347.html