STM32 UART(接收 ,发送数据)

UART接收发送数据:

平台:STM32F401 discovery版

此代码用的UART6,TX,RX对应的PIN脚是PC6,PC7

如图:

STM32 UART(接收 ,发送数据)_第1张图片


代码如下:

步骤一:初始化串口的GPIO,USART,并且配置上UART的RX中断

void USART6_Config(void)
{
   USART_InitTypeDef USART_InitStructure;
   NVIC_InitTypeDef NVIC_InitStructure;
  GPIO_InitTypeDef GPIO_InitStructure;
  
    /* Enable GPIO clock */
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC , ENABLE);
  
  /* Enable USART clock */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6, ENABLE);
  
  /* Connect USART pins to  */
  GPIO_PinAFConfig(GPIOC, GPIO_PinSource6, GPIO_AF_USART6);
  GPIO_PinAFConfig(GPIOC, GPIO_PinSource7, GPIO_AF_USART6);
  
  /* Configure USART Tx and Rx as alternate function push-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);
  
  /* USARTx configuration ----------------------------------------------------*/ 
  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);
  
  /* Enable the USARTx Interrupt */
  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,所以需要重定向一下

int fputc(int ch, FILE *f)
{
  USART_SendData(USART6, (unsigned char) ch);
  while (!(USART6->SR & USART_FLAG_TXE));
  return (ch);
	
}


int fgetc(FILE *f)
{
  while (USART_GetFlagStatus(USART6, USART_FLAG_RXNE) == RESET);

  return (int)USART_ReceiveData(USART6);
}
步骤三:编写RX中断函数

void USART6_IRQHandler(void)
{
  uint8_t ch;
  if(USART_GetITStatus(USART6, USART_IT_RXNE) != RESET)
  { 	
      ch = USART_ReceiveData(USART6);
      printf( "%c\n", ch ); 
    } 
}
注意地方:使用的IAR,冲定向的时候出现FILE类型找不到,可是在C原因中#include ,但是为什么还是报错呢?

追代码发现:

#if _DLIB_FILE_DESCRIPTOR
  typedef _Filet FILE;
#endif /* _DLIB_FILE_DESCRIPTOR */

_DLIB_FILE_DESCRIPTOR宏是0,但是IAR又不让修改,所以肯定是哪里的lib没有配置,于是找到如图就搞定了

STM32 UART(接收 ,发送数据)_第2张图片

附一张板子图:

STM32 UART(接收 ,发送数据)_第3张图片

用标准的杜邦线连接


整个工程如连接:

http://download.csdn.net/detail/xiaoxiaopengbo/9425422

你可能感兴趣的:(STM32 UART(接收 ,发送数据))