STM32 printf重新導向

來源:互聯網
上載者:User

 

STM32串口通訊中使用printf發送資料配置方法(開發環境 Keil RVMDK)

標籤:  STM32  串口通訊  printf方法  2011-06-29 23:29 

在STM32串口通訊程式中使用printf發送資料,非常的方便。可在剛開始使用的時候總是遇到問題,常見的是硬體訪真時無法進入main主函數,其實只要簡單的配置一下就可以了。

 

下面就說一下使用printf需要做哪些配置。

 

有兩種配置方法:

一、對工程屬性進行配置,詳細步驟如下

1、首先要在你的main 檔案中 包含“stdio.h” (標準輸入輸出標頭檔)。

2、在main檔案中重定義<fputc>函數    如下:

   // 發送資料

   int fputc(int ch, FILE *f)

   {

      USART_SendData(USART1, (unsigned char) ch);// USART1 可以換成 USART2 等

      while (!(USART1->SR & USART_FLAG_TXE));

      return (ch);

   }

   // 接收資料

   int GetKey (void)  { 

      while (!(USART1->SR & USART_FLAG_RXNE));

      return ((int)(USART1->DR & 0x1FF));

   }

   這樣在使用printf時就會調用自訂的fputc函數,來發送字元。

3、在工程屬性的 “Target" -> "Code Generation" 選項中勾選 "Use MicroLIB"” 

   MicroLIB 是預設C的備份庫,關於它可以到網上尋找詳細資料。

 

至此完成配置,在工程中可以隨意使用printf向串口發送資料了。

 

二、第二種方法是在工程中添加“Regtarge.c”檔案

1、在main檔案中包含 “stdio.h” 檔案

2、在工程中建立一個檔案儲存為 Regtarge.c , 然後將其添加工程中

在檔案中輸入如下內容(直接複製即可)

#include <stdio.h>

#include <rt_misc.h>

#pragma import(__use_no_semihosting_swi)

extern int  SendChar(int ch); // 聲明外部函數,在main檔案中定義

extern int  GetKey(void);

struct __FILE {

  int handle;                 // Add whatever you need here 

};

FILE __stdout;

FILE __stdin;

int fputc(int ch, FILE *f) {

  return (SendChar(ch));

}

int fgetc(FILE *f) {

  return (SendChar(GetKey()));

}

void _ttywrch(int ch) {

 SendChar (ch);

}

int ferror(FILE *f) {                            // Your implementation of ferror

  return EOF;

}

void _sys_exit(int return_code) {

label:  goto label;           // endless loop

}

 

3、在main檔案中添加定義以下兩個函數

int SendChar (int ch)  {

  while (!(USART1->SR & USART_FLAG_TXE)); // USART1 可換成你程式中通訊的串口

  USART1->DR = (ch & 0x1FF);

  return (ch);

}

int GetKey (void)  {

  while (!(USART1->SR & USART_FLAG_RXNE));

  return ((int)(USART1->DR & 0x1FF));

}

至此完成配置,可以在main檔案中隨意使用 printf 。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.