Original address: http://blog.csdn.net/yannanxiu/article/details/52438351
Overview
We will need to print debugging information when we are developing C/d, we are accustomed to use printf function when we print debugging information, but in Keil C51 environment, because our program is downloaded to SCM, we can not directly print to the serial port when using printf function. This time, we need to redirect the output of the printf function. redirect
Redirecting printf is simple, and we know that the printf function calls Putchar to implement character data transfer. As long as we rewrite the Putchar function, we can redirect the printf input output. Code Listing
Here are the code listings for testing printf redirection with a single-chip microcomputer in the Keil 5 environment STC12
#include <stc12c5a60s2. h> #include <stdio.h>//uart1 initialize void uart1init (void)//115200bps@11.0592mhz {PCON &= 0x7F; Baud rate SCON = 0x50; 8-bit data, variable baud rate auxr |= 0x04; 1T mode BRT = 0xFD; Set the independent baud rate generator reload value AUXR |=0x01; Serial 1 Select the independent generator for the baud rate generator AUXR |=0x10; Start independent baud rate Generator ES = 1; Enable serial port 1 interrupt}//uart1 to send serial data void Uart1_senddata (char dat) {es=0;
Shut down the serial port interrupt Sbuf=dat; while (ti!=1); Wait for the sending success ti=0; Clear send interrupt flag Es=1; Open serial Interrupt}//uart1 send string void uart1_sendstring (char *s) {while (*s)//detect string Terminator {Uart1_senddata (*s++);//Send when
Pre-character}}//override Putchar function char Putchar (char c) {uart1_senddata (c);
return C;
} void Main (void) {uart1init ();
Uart1_sendstring ("Hello world!\r\n");
printf ("printf test!\r\n");
printf ("Complie time:%s\r\n", __time__); while (1) {}}
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 52 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 3 6 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
Open the serial port to turn the baud rate to 115200bps, you can see the serial port printing the following information:
Hello world!
printf test!
Complie time:11:12:36