天天看點

STM32--STM32CubeMX生成USART作為序列槽使用

一. CubeMX設定

STM32--STM32CubeMX生成USART作為序列槽使用
STM32--STM32CubeMX生成USART作為序列槽使用

二. 代碼實作

(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 */
}
           

繼續閱讀