STM32F334使用串口發(fā)送接收數(shù)據(jù)
MCU:STM32F334C8T6
Frameware:STM32F3348-Discovery_FW_V1.0.0
實現(xiàn)功能:
在PC使用串口調(diào)試助手向MCU發(fā)送字符(數(shù)據(jù)),MCU將接收到的字符發(fā)回PC
代碼:
#include"main.h"
intmain()
{
GPIO_Config();
USART_Config();
NVIC_Config();
while(1);
}
voidGPIO_Config()
{
GPIO_InitTypeDefGPIO_InitStructure;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB,ENABLE);
GPIO_InitStructure.GPIO_Pin=(GPIO_Pin_3|GPIO_Pin_4);//USART2對應的RX,TX引腳
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF;//復用模式
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType=GPIO_OType_PP;//推挽輸出
GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_UP;
GPIO_Init(GPIOB,&GPIO_InitStructure);
//配置復用功能
GPIO_PinAFConfig(GPIOB,GPIO_PinSource3,GPIO_AF_7);
GPIO_PinAFConfig(GPIOB,GPIO_PinSource4,GPIO_AF_7);
}
voidUSART_Config()
{
USART_InitTypeDefUSART_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
USART_DeInit(USART2);
USART_InitStructure.USART_BaudRate=115200;
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_Rx|USART_Mode_Tx;
USART_Init(USART2,&USART_InitStructure);
USART_ITConfig(USART2,USART_IT_RXNE,ENABLE);//使能中斷
USART_ClearFlag(USART2,USART_FLAG_TC);
USART_Cmd(USART2,ENABLE);//打開串口
}
voidNVIC_Config()
{
NVIC_InitTypeDefNVIC_InitStruct;
#ifdefVECT_TAB_SRAM
NVIC_SetVectorTable(NVIC_VectTab_RAM,0x0);//一定要設置中斷向量表,否則可能出錯
#else
NVIC_SetVectorTable(NVIC_VectTab_FLASH,0x0);
#endif
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitStruct.NVIC_IRQChannel=USART2_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority=0;
NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStruct);
}
//中斷處理函數(shù)
voidUSART2_IRQHandler(void)
{
if(USART_GetFlagStatus(USART2,USART_FLAG_RXNE)==SET)
{
USART_SendData(USART2,USART_ReceiveData(USART2));//發(fā)送接收到的數(shù)據(jù)
while(!USART_GetFlagStatus(USART2,USART_FLAG_TC));
}
USART_ClearITPendingBit(USART2,USART_IT_RXNE);//清中斷標志位
}