天天看點

STM32CubeMx開發之路—3發送USART資料和printf重定向 STM32CubeMx開發之路—3發送USART資料和printf重定向

STM32CubeMx開發之路—3發送USART資料和printf重定向

運作環境

  • Windows10
  • STM32CubeMX___Version 5.0.0
  • Keil5(MDK5)___Version 5.15

簡介

本例程主要講解如何通過序列槽發送資料和重定向printf

STM32CubeMx基本配置

基礎配置過程請參考 STM32CubeMx(Keil5)開發之路—1配置第一個項目

STM32CubeMx USART1配置

1——點選USART1進行設定

2——模式選擇Asynchronous異步傳輸

3——可以看到右邊自動出現了Tx和Rx

4——可以自行設定波特率,停止位,校驗位等參數

STM32CubeMx開發之路—3發送USART資料和printf重定向 STM32CubeMx開發之路—3發送USART資料和printf重定向

代碼修改

1——選擇main.c檔案

2——在USER CODE中添加如下代碼,重定向printf

int fputc(int ch, FILE *f)
{
    HAL_UART_Transmit(&huart1, (uint8_t *)&ch,1, 0xFFFF);
    return ch;
}
           
STM32CubeMx開發之路—3發送USART資料和printf重定向 STM32CubeMx開發之路—3發送USART資料和printf重定向

在主循環中添加如下代碼

int num=99;
	  char tx_buf[]={"HelloWorld!"};
	  
	  printf("\nnum = %d\n",num);
	  HAL_Delay(1000);
	  HAL_UART_Transmit(&huart1, (unsigned char*)tx_buf,11,10);
	  HAL_Delay(1000);
           
STM32CubeMx開發之路—3發送USART資料和printf重定向 STM32CubeMx開發之路—3發送USART資料和printf重定向

燒錄代碼後打開出口調試助手,正确的話會看到如下輸出

STM32CubeMx開發之路—3發送USART資料和printf重定向 STM32CubeMx開發之路—3發送USART資料和printf重定向

小結

序列槽常用場合

  • 列印調試
  • 進行序列槽通信
  • 對某些晶片的讀取

本節主要講序列槽發送和printf的重定向,沒有對序列槽接收進行講解,後續可能會在DMA章節一起講解,敬請期待。