Use printf to output stream on STM32F4
It would be nice, if you can simply just use printf to direct output strings to USART, LCD, etc. With ARM C, you are able to do this. You just need to implement some things and you are ready to work.
New STDIO library is available here.
To enable printf functionality, first you need to create a new __FILE struct. This struct is then called with FILE struct. It can have only one dummy parameter, but it has to be created, because you need pointer to this structure if you want to output characters to stream. If you need any control for this, you can create your own. I created my own below:
1 2 3 4 5 |
/* We need to implement own __FILE struct */ /* FILE struct is used from __FILE */ struct __FILE { int dummy; }; |
After that, we have to create a variable with FILE struct:
1 2 3 |
/* You need this if you want use printf */ /* Struct FILE is implemented in stdio.h */ FILE __stdout; |
Variable name __stdout is important. You can not use different name, otherwise printf will not work. Last thing we need to create is a function, that will be automatically called from printf and will actually print your charater by character to stream. Function has fixed name and can not be changed.
1 2 3 4 5 6 7 8 9 10 |
int fputc(int ch, FILE *f) { /* Do your stuff here */ /* Send your custom byte */ /* If everything is OK, you have to return character written */ return ch; /* If character is not correct, you can return EOF (-1) to stop writing */ //return -1; } |
You are ready to use printf function. Below is simple example, that will output data to USART1 with printf using my USART library.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
/** * @author Tilen Majerle * @email tilen@majerle.eu * @website http://stm32f4-discovery.net * @ide Keil uVision 5 */ /* Include core modules */ #include "stm32f4xx.h" /* Include my libraries here */ #include "defines.h" #include "tm_stm32f4_usart.h" /* In stdio.h file is everything related to output stream */ #include "stdio.h" /* We need to implement own __FILE struct */ /* FILE struct is used from __FILE */ struct __FILE { int dummy; }; /* You need this if you want use printf */ /* Struct FILE is implemented in stdio.h */ FILE __stdout; int fputc(int ch, FILE *f) { /* Do your stuff here */ /* Send your custom byte */ /* Send byte to USART */ TM_USART_Putc(USART1, ch); /* If everything is OK, you have to return character written */ return ch; /* If character is not correct, you can return EOF (-1) to stop writing */ //return -1; } int main(void) { /* Initialize system */ SystemInit(); /* Initialize USART1, TX: PA9 */ TM_USART_Init(USART1, TM_USART_PinsPack_1, 115200); /* Put string to USART1 */ printf("USART1 Stream\n"); while (1) { } } |
You will need my USART library for this, download below.
USART library for all USART peripherals
Recent comments