STM32CubeMX:UART操作

UART共有三种操作方式,轮询方式、中断方式以及DMA方式。

芯片:STM32F103C8T6

应用管脚:

输出:PA0、PA1

USART1

配置界面

STM32CubeMX:UART操作_第1张图片

添加中断配置

STM32CubeMX:UART操作_第2张图片

添加DMA配置

STM32CubeMX:UART操作_第3张图片

代码应用

1.实现printf函数

/* USER CODE BEGIN 0 */
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
   set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/* USER CODE END 0 */


/* USER CODE BEGIN 4 */
/**
  * @brief  Retargets the C library printf function to the USART.
  * @param  None
  * @retval None
  */
PUTCHAR_PROTOTYPE
{
  /* Place your implementation of fputc here */
  /* e.g. write a character to the USART1 and Loop until the end of transmission */
  HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
  return ch;
}
/* USER CODE END 4 */

2.轮询方式发送与接收

发送数据

uint8_t senddata[20]="This use Transmit.\r\n";  
if(HAL_UART_Transmit(&huart1,senddata,sizeof(senddata),0xFFFF) != HAL_OK)
  {
    /* Transfer error in reception process */
    Error_Handler();
  }

轮询接收采用阻塞式超时接收模式

  uint8_t huart1_RxBuffer[20];
  HAL_UART_Receive(&huart1, huart1_RxBuffer, 20,0x10);
3.中断方式发送与接收

增加接收中断回调函数

/* USER CODE BEGIN 4 */
/**
  * @brief  Rx Transfer completed callbacks.
  * @param  huart: Pointer to a UART_HandleTypeDef structure that contains
  *                the configuration information for the specified UART module.
  * @retval None
  */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
	if(huart==&huart1)
	{
		Rx_flag=1;
		HAL_GPIO_WritePin(GPIOA,GPIO_PIN_0,(GPIO_PinState)!HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0));
		
//		if(HAL_UART_Receive_IT(&huart1, (uint8_t *)huart1_RxBuffer, Rx_size) != HAL_OK)
//		{
//			/* Transfer error in reception process */
//			Error_Handler();
//		}
	}
}

/* USER CODE END 4 */
发送数据

uint8_t senddata_IT[23]="This use Transmit IT.\r\n";	
if(HAL_UART_Transmit_IT(&huart1,senddata_IT, sizeof(senddata_IT)) != HAL_OK)
	{
		/* Transfer error in reception process */
		Error_Handler();
	}
接收数据,调用此函数后,接收中断可执行一次。

uint8_t huart1_RxBuffer[20];	
if(HAL_UART_Transmit_DMA(&huart1,senddata_DMA, sizeof(senddata_DMA))!= HAL_OK)
	{
		Error_Handler();
	}

if(HAL_UART_Receive_IT(&huart1, (uint8_t *)huart1_RxBuffer, Rx_size) != HAL_OK) {/* Transfer error in reception process */ Error_Handler(); }

 3.DMA方式发送与接收 
  

增加接收中断回调函数(与中断方式相同)

发送数据

uint8_t senddata_DMA[24]="This use Transmit DMA.\r\n";
	if(HAL_UART_Receive_DMA(&huart1, (uint8_t *)huart1_RxBuffer, Rx_size) != HAL_OK)
  {
    /* Transfer error in reception process */
    Error_Handler();
  }

接收数据(特征与中断方式相同)
	if(HAL_UART_Receive_DMA(&huart1, (uint8_t *)huart1_RxBuffer, Rx_size) != HAL_OK)
  {
    /* Transfer error in reception process */
    Error_Handler();
  }

你可能感兴趣的:(STM32CubeMX)