Stm32 serial communication uses printf to send data configuration

Development environment: Keil RVMDK

It is very convenient to use printf to send data in the STM32 serial communication program. You can always encounter problems when you first use it. It is common to not enter the main main function when the hardware accesses the real. In fact, you can simply configure it. Let's talk about what configuration you need to do with printf.

There are two ways to configure it:

First, configure the project properties, the detailed steps are as follows

1. First, include "stdio.h" (standard input and output header file) in your main file.

[size=12.8000001907349px]2, redefine the "fputc" function in the main file as follows

// send data

Int fputc(int ch, FILE *f)

{

USART_SendData(USART1, (unsigned char) ch);// USART1 can be replaced by USART2, etc.

While (!(USART1-"SR & USART_FLAG_TXE));

Return (ch);

}

// Receive data

Int GetKey (void)

{

While (!(USART1-"SR & USART_FLAG_RXNE));

Return ((int)(USART1-"DR & 0x1FF));

}

This will call the custom fputc function to send characters when using printf.

3. Check "Use MicroLIB" in the "Target" - "Code GeneraTIon" option of the project properties. MicroLIB is the default C backup library. You can go to the Internet to find detailed information.

Second, the second method is to add the "Regtarge.c" file to the project.

1. Include the "stdio.h" file in the main file.

[size=12.8000001907349px]2, create a file in the project and save it as Regtarge.c, then add it to the project and enter the following content in the file (copy it directly)

#include "stdio.h"

#include "rt_misc.h"

#pragma import(__use_no_semihosTIng_swi)

Extern int SendChar(int ch); // Declare an external function, defined in the main file

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

}

[size=12.8000001907349px]3, add the following two functions defined in the main file

Int SendChar (int ch) {

While (!(USART1-"SR & USART_FLAG_TXE)); // USART1 can be replaced with the serial port for communication in your program

USART1-"DR = (ch & 0x1FF);

Return (ch);

}

Int GetKey (void) {

While (!(USART1-"SR & USART_FLAG_RXNE));

Return ((int)(USART1-"DR & 0x1FF));

}

Now that the configuration is complete, you can use printf freely in the main file.

Square Glass Panoramic Elevator

Glass Lift,Sight Seeing Elevator,Square Panoramic Elevator,Square Panoramic Elevator With Glass

XI'AN TYPICAL ELEVATOR CO., LTD , https://www.chinaxiantypical.com