2016-10-02 66 views
0

我使用的重新定位printf()這個代碼,但它不工作如何重定向STM32F10x上的printf()?

#ifdef __GNUC__ 
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf 
    set to 'Yes') calls __io_putchar() */ 
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch) 
#else 
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f) 
#endif /* __GNUC__ */ 

PUTCHAR_PROTOTYPE 
{ 
    /* Place your implementation of fputc here */ 
     /* e.g. write a character to the LCD */ 
    lcd_Data_Write((u8)ch); 

     return ch; 
} 

我用STM32F103RBT6

編譯器:GCC與emBitz編輯

+0

可能是重複http://stackoverflow.com/questions/39664071/how-to-make-printf-work-on-stm32f103/ – SamR

+0

可能是有用的:http://electronics.stackexchange.com/questions/206113/how-do-i-use-the-printf-function-on-stm32 –

回答

1

坦克你本斯Kaulics

我用tinyprintf庫,它工作得很好:github link

1

作爲替代,您可以編寫自己的printf()功能使用,Variable Argument Functions(va_list)

隨着va_list定製打印功能如下所示:

#include <stdio.h> 
#include <stdarg.h> 
#include <string.h> 

void vprint(const char *fmt, va_list argp) 
{ 
    char string[200]; 
    if(0 < vsprintf(string,fmt,argp)) // build string 
    { 
     HAL_UART_Transmit(&huart1, (uint8_t*)string, strlen(string), 0xffffff); // send message via UART 
    } 
} 

void my_printf(const char *fmt, ...) // custom printf() function 
{ 
    va_list argp; 
    va_start(argp, fmt); 
    vprint(target, fmt, argp); 
    va_end(argp); 
} 

用例:

uint16_t year = 2016; 
uint8_t month = 10; 
uint8_t day = 02; 
char* date = "date"; 

// "Today's date: 2015-12-18" 
my_printf("Today's %s: %d-%d-%d\r\n", date, year, month, day); 

注意的是,雖然該解決方案爲您提供了方便的功能來使用,它比發送原始慢數據或甚至使用sprintf()。我已經在AVR和STM32微控制器上使用了這個解決方案。

你可以進一步修改vprint這個樣子,哪裏periphery_t是一個簡單的enum類型:

void vprint(periphery_t target, const char *fmt, va_list argp) 
{ 
    char string[200]; 
    if(0 < vsprintf(string,fmt,argp)) 
    { 
     switch(target) 
     { 
      case PC: PC_send_str(string); 
       break; 
      case GSM: GSM_send_str(string); 
       break; 
      case LCD: LCD_print_str(string); 
       break; 
      default: LCD_print_str(string); 
       break; 
     } 
    } 
} 
2

嘗試劫持_write函數,如下所示:

#define STDOUT_FILENO 1 
#define STDERR_FILENO 2 

int _write(int file, char *ptr, int len) 
{ 
    switch (file) 
    { 
    case STDOUT_FILENO: /*stdout*/ 
     // Send the string somewhere 
     break; 
    case STDERR_FILENO: /* stderr */ 
     // Send the string somewhere 
     break; 
    default: 
     return -1; 
    } 
    return len; 
} 
+0

我在STM32F072上使用這種方法。詳情在這裏。 http://electronics.stackexchange.com/questions/206113/how-do-i-use-the-printf-function-on-stm32/279945#279945 –