How to configure data transmission using printf in stm32 Serial Communication (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 using it at the beginning. The common problem is that you cannot enter the main function when accessing the hardware. In fact, you only need to simply configure it. The following describes the configurations required to use printf. There are two configuration methods: 1. Configure project properties as follows: 1. First, you must include "stdio. H" in your main file (standard input/output header file ). 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 changed to usart2. While (! (Usart1-> Sr & usart_flag_txe )); Return (CH ); } // Receive data Int getkey (void ){ While (! (Usart1-> Sr & usart_flag_rxne )); Return (INT) (usart1-> dr & 0x1ff )); } In this way, the custom fputc function is called to send characters when printf is used. 3. Select "use microlib" in the "target"-> "code generation" option of the Project attribute "" Microlib is the default C backup database. You can go to the Internet to find details about it. Now that the configuration is complete, you can use printf to send data to the serial port at will in the project. 2. The second method is to add the "regtarge. c" file to the project. 1. Include the "stdio. H" file in the main file. 2. Create a file in the project and save it as regtarge. C. Then add it to the Project 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 } 3. Add and define the following two functions in the main file: Int sendchar (INT ch ){ While (! (Usart1-> Sr & usart_flag_txe); // usart1 can be replaced with the serial port used 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 in the main file at will. |