當前位置:編程學習大全網 - 編程語言 - stm32編程怎麽使用printf函數

stm32編程怎麽使用printf函數

有兩種配置方法:

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

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

2、在main文件中重定義函數如下:

// 發送數據

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

#include

#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 。

  • 上一篇:電子信息工程畢業後是幹什麽的?
  • 下一篇:機器人創客是學什麽的
  • copyright 2024編程學習大全網