STM32--STM32CubeMX生成USART作为串口使用

一. CubeMX设置

二. 代码实现

(1)实现代码重定向,使用printf打印数据,在usart.c中加入如下代码

/* USER CODE BEGIN 1 */

//!=============================================================================
//!				        Function Define Section(as bellows)
//!=============================================================================

/*!
@Brief
	Redirect the C library function printf to USARTx
@Param
	ch		[character to send]
	f			[file point]
@Return
	ch		[character to send]
*/
int fputc(int ch, FILE *f)
{
    HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, 0xffff);
    return ch;
}
 
/*!
@Brief
	Redirect the C library function getchar,scanf to USARTx
@Param
	f			[file point]
@Return
	ch		[character to receive]
*/
int fgetc(FILE *f)
{
    uint8_t ch = 0;
    HAL_UART_Receive(&huart2, &ch, 1, 0xffff);
    return ch;
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if(huart->Instance == USART1)
    {
        //HAL_UART_Transmit(&huart1, (uint8_t *)Buffer, 16, 0xffff);  //×èÈûģʽ
		HAL_UART_Transmit_IT(&huart2, (uint8_t *)ucUSART_RecvBuffer, 16);
        HAL_UART_Receive_IT(&huart2, (uint8_t *)ucUSART_RecvBuffer, 16);
    }
}
/* USER CODE END 1 */

 在usart.h中加入如下代码

/* USER CODE BEGIN Includes */
#include <stdio.h>
/* USER CODE END Includes */

 (2)main实现调用串口的程序

int main(void)
{
  /* USER CODE BEGIN 1 */
	uint8_t  Data[5]={1, 2, 3, 4, 5};  //test code
	uint16_t CanID=0x001;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  //MX_CAN1_Init();
  MX_ADC1_Init();
  MX_TIM2_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */
	//Enable timer2
	//HAL_TIM_Base_Start_IT(&htim2);
	//Initialize CAN and filter and start the CAN
	//CAN_User_Init(&hcan1);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {	
	//CANx_SendNormalData(&hcan1, CanID, Data, 5); 
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		float fData = 1.33;
		int iData = 99;
	    char tx_buf[] = {"HelloWorld!"};
	  
	   printf("App Start!!!!!!!!!!!\r\n");
	   printf("iData = %d\r\n", iData);
	   printf("fData = %f\r\n", fData);
	  //HAL_Delay(1000);
	  //HAL_UART_Transmit(&huart2, (unsigned char*)tx_buf, 11, 10);
	  HAL_Delay(1000);
  }
  /* USER CODE END 3 */
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值