stm32f0串口编程

问题描述 投票:0回答:1

我试图让usart在我的stm32f0-discovery上工作,但现在我发现有关这方面的文档有点“缺乏”,所以有人有任何usart为stm32f050工作的例子吗?

谢谢。

巴特·托尼森

stm32 uart stm32f4discovery usart
1个回答
9
投票

好吧,在网上搜索了两天后。我找到了这段小代码,并设法让它工作:

  USART_InitTypeDef USART_InitStructure;
  GPIO_InitTypeDef GPIO_InitStructure;

  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);

  GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_1);
  GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_1);

  //Configure USART2 pins:  Rx and Tx ----------------------------
  GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_2 | GPIO_Pin_3;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
  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_Rx | USART_Mode_Tx;
  USART_Init(USART2, &USART_InitStructure);

  USART_Cmd(USART2,ENABLE);

  while(1)
  {
   while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);

   USART_SendData(USART2, 'X');
  }
}

*注:该串口使用PA2和PA3引脚(RX和TX)。

当uart的sendbuffer的缓冲区为空时,它发送一个X。更好的是,这段代码只使用了 stm32f0xx.h 文件。所以它去掉了任何不必要的部分。

希望有人也可以使用这个,因为我花了很多努力才找到这个简单的代码。也许有一天我会写一篇关于使用 stm32f0 进行 uart 编程的指南。

*编辑:

我确实写过一篇关于usart的教程。可以在这里找到:

usart stm32f0教程 希望这可以帮助很多人。

© www.soinside.com 2019 - 2024. All rights reserved.