STM32F334使用串口发送接收数据

MCU:STM32F334C8T6

Frameware:STM32F3348-Discovery_FW_V1.0.0

实现功能:

在PC使用串口调试助手向MCU发送字符(数据),MCU将接收到的字符发回PC

代码:

#include "main.h"

int main()
{
	GPIO_Config();
	USART_Config();
	NVIC_Config();

	while(1);
}

void GPIO_Config()
{
	GPIO_InitTypeDef GPIO_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);


}

void USART_Config()
{
	USART_InitTypeDef USART_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);    //打开串口
}
void NVIC_Config()
{
	NVIC_InitTypeDef NVIC_InitStruct;
	
#ifdef  VECT_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);
}

//中断处理函数
void USART2_IRQHandler (void)
{
	if (USART_GetFlagStatus(USART2,USART_FLAG_RXNE) ==SET)
	{
	
		USART_SendData(USART2,USART_ReceiveData(USART2));//发送接收到的数据
		while (!USART_GetFlagStatus(USART2,USART_FLAG_TC));
	}
	USART_ClearITPendingBit(USART2,USART_IT_RXNE);//清中断标志位
}


wind

2015,03,29


你可能感兴趣的:(STM32,STM32学习笔记)