Reputation: 1103
I want use the function printf
to print character on the serial port. I have read these 2 posts 1 and 2, But I'am not sure to understand the manip:
in the 1st link it's said:
To enable printf functionality, first you need to create a new __FILE
struct. This struct is then called with FILE struct.
Why I have to create __FILE
struct I didn't realy undrestand this sentence.
In the 2nd link it's said
To complete the separation from the standard I/O library we also have had to redefine __stdout
and __stdin
. These can be found inside the retarget.c file below the declaration of the __FILE
structure.
If I redefine these 2 variables isn't that a compilation error I mean a redefinition.
Upvotes: 0
Views: 7521
Reputation: 61
Add this piece of code in your code
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE * f)
#endif
PUTCHAR_PROTOTYPE {
HAL_UART_Transmit( & huart2, (uint8_t * ) & ch, 1, 0xFFFF);
return ch;
}
Only thing to edit is this line, set it as per your device serial port driver
HAL_UART_Transmit( & huart2, (uint8_t * ) & ch, 1, 0xFFFF);
Upvotes: 0
Reputation: 399
This may possibly a duplication of How to make printf work on STM32F103?
I will put my answer, which I posted in the above thread, here too, anyway.
Writing an own printf
implementation is an option, and probably the most recommended option according to me. Get some inspiration from the standard library implementation and write your own version, only to cater your requirements. In general, what you have to do is, first retarget a putc
function to send char s through your serial interface. Then override the printf
method by using the putc
custom implementation. Perhaps, a very simple approach is sending the string character-wise by recursive calls for putc
function.
Last but not least, you can find some lightweight printf
implementations. The code size and the set of features offered by these lightweight implementations lie in between the custom written printf
function and the stock standard prinf
function (aka the beast). I have recently tried this and very pleased with its performance on an ARM core in terms of memory footprint and the number of execution cycles required. http://www.sparetimelabs.com/tinyprintf/tinyprintf.php
-PS
Copied from my own writings sometime back - http://mycola.info/2015/02/09/lightweight-printfscanf-for-embedded-applications/
Upvotes: 1