Use printf to output stream on STM32F4

来源:互联网 发布:2016版excel数据有效性 编辑:程序博客网 时间:2024/05/21 06:54

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.

To enable printf functionality, first you need to create a new __FILE struct. This struct is then called with FILEstruct. 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:

/* 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:

/* 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.

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

/* 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) {}}