STM32 UART(接收 ,发送数据)
扫描二维码
随时随地手机看文章
UART接收发送数据:
平台:STM32F401 discovery版
此代码用的UART6,TX,RX对应的PIN脚是PC6,PC7
如图:
步骤一:初始化串口的GPIO,USART,并且配置上UART的RX中断
voidUSART6_Config(void)
{
USART_InitTypeDefUSART_InitStructure;
NVIC_InitTypeDefNVIC_InitStructure;
GPIO_InitTypeDefGPIO_InitStructure;
/*EnableGPIOclock*/
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC,ENABLE);
/*EnableUSARTclock*/
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6,ENABLE);
/*ConnectUSARTpinsto*/
GPIO_PinAFConfig(GPIOC,GPIO_PinSource6,GPIO_AF_USART6);
GPIO_PinAFConfig(GPIOC,GPIO_PinSource7,GPIO_AF_USART6);
/*ConfigureUSARTTxandRxasalternatefunctionpush-pull*/
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;//GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType=GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_6;
GPIO_Init(GPIOC,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_7;
GPIO_Init(GPIOC,&GPIO_InitStructure);
/*USARTxconfiguration----------------------------------------------------*/
USART_InitStructure.USART_BaudRate=115200;//5250000;
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(USART6,&USART_InitStructure);
/*EnabletheUSARTxInterrupt*/
NVIC_InitStructure.NVIC_IRQChannel=USART6_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority=0;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_ITConfig(USART6,USART_IT_RXNE,ENABLE);
USART_Cmd(USART6,ENABLE);
}
步骤二:测试一下TX,即用printf,但是printf内部是调用fputs,所以需要重定向一下
intfputc(intch,FILE*f)
{
USART_SendData(USART6,(unsignedchar)ch);
while(!(USART6->SR&USART_FLAG_TXE));
return(ch);
}
intfgetc(FILE*f)
{
while(USART_GetFlagStatus(USART6,USART_FLAG_RXNE)==RESET);
return(int)USART_ReceiveData(USART6);
}
步骤三:编写RX中断函数
[cpp]view plaincopy
voidUSART6_IRQHandler(void)
{
uint8_tch;
if(USART_GetITStatus(USART6,USART_IT_RXNE)!=RESET)
{
ch=USART_ReceiveData(USART6);
printf("%cn",ch);
}
}
注意地方:使用的IAR,冲定向的时候出现FILE类型找不到,可是在C原因中#include
追代码发现:
#if _DLIB_FILE_DESCRIPTOR
typedef _Filet FILE;
#endif /* _DLIB_FILE_DESCRIPTOR */
_DLIB_FILE_DESCRIPTOR宏是0,但是IAR又不让修改,所以肯定是哪里的lib没有配置,于是找到如图就搞定了
附一张板子图:
用标准的杜邦线连接
整个工程如连接:
http://download.csdn.net/detail/xiaoxiaopengbo/9425422