Key points of using printf() function in keil
When searching for information online, I found an article introducing the use of printf() function in keil. I copied it here as a memo.
In Keil, printf sends data to the serial port by default. Therefore, if you use this function, you must initialize the serial port first, otherwise it may cause a crash. In addition, TI should be set before printf. The reasons are as follows:
1. The printf function calls the putchar function for input, and putchar should first determine whether ti is 1. If not, it waits for it to be 1. If it is 1, it clears it to 0 and then sends a character. Therefore, if you use the printf function directly, your program will wait for ti to be 1 in the putchar function. At this time, your program is equivalent to being dead. You can achieve your goal by rewriting the putchar function.
2. Keil's serial port processing is quite clever. My analysis is as follows:
In putchar.c, TI is checked before sending. The purpose of this is to leave as much time as possible for the program between two serial port operations, rather than wasting the time waiting for the byte to be sent. Therefore, when the system is initialized, TI=1 must be set; then the printf function can be used smoothly. The method of using sbuf=" " is actually to set TI=1. In addition, it should be noted that after the printf function is executed, the last byte is not sent. For example, in 485 communication, if it is switched to receiving mode at this time, the last byte will be lost.
3. Generally, the serial port sends the next byte after TI (byte transmission completion flag) is 1. Since both the interrupt and the TI flag query method will detect TI, the TI flag must be set for the first transmission to start the serial port transmission. The final effect of your "put a character in the serial port data register SBUF in the initialization part of the program to start terminal display;" method is to set TI to 1, and changing it to TI=1 to start transmission is the same (of course, the ' ' character will not be sent).
4. Defined in Here is a simple example: //=========================== #include #include //------------------------------- int main() { Uart_init(); //Initialize the serial port. No specific code will be written here. TI = 1; //keil must be set before calling the printf function in stdio.h. while(1) { printf("Hello world!n"); delay_ms(800); //Delay program, no specific code will be written here. } return 0; } ------------------------------ printf http://www.keil.com/support/man/docs/c51/c51_printf.htm Home »Library Reference »Reference » printf Summary #include int printf ( const char *fmtstr /* format string */ <[>, arguments ... <]>); /* additional arguments */ Description The printf function formats a series of strings and numeric values and builds a string to write to the output stream using theputchar function. Thefmtstr argument is a format string that may be composed of characters, escape sequences, and format specifications. Ordinary characters and escape sequences are copied to the stream in the order in which they are interpreted. Format specifications always begin with a percent sign ('%') and require that additionalarguments are included in the printf function call. The format string is read from left to right. The first format specification encountered references the firstargument afterfmtstr and converts and outputs it using the format specification. The second format specification accesses the secondargument afterfmtstr, and so on. If there are morearguments than format specifications, extraarguments are ignored. Results are unpredictable if there are not enougharguments for the format specifications or if the argument types do not match those specified byfmtstr. Format specifications have the following general format: % <[>flags<]> <[>width<]> <[>.precision<]> <[>{b|B|l|L}<]> type Each field in the format specification may be a single character or a number which specifies a particular format option. The type field is a single character that specifies whether the argument is interpreted as a character, string, number, or pointer, as shown in the following table. Type Argument Type Input Format d int Signed decimal number. u unsigned int Unsigned decimal number. o unsigned int Unsigned octal number. x unsigned int Unsigned hexadecimal number using "0123456789abcedf". X unsigned int Unsigned hexadecimal number using "0123456789ABCDEF". f float Floating-point number formatted as < [>-<]>dddd.dddd. e float Floating-point number formatted as < [>-<]>d.dddde<[>-<]>dd. E float Floating-point number formatted as < [>-<]>d.ddddE<[>-<]>dd. g float Floating-point number using either the e or f format, whichever is more compact for the specified value and precision. G float Floating-point number using either the E or f format, whichever is more compact for the specified value and precision. c char A single character. s * A string of characters terminated by a null character (''). p * A generic pointer formatted as t:aaaa wheret is the memory type andaaaa is the hexadecimal address. Note The optional characters l or L may immediately precede the type character to respectively specify long types for d, i, u, o, x, and X. The optional characters b or B may immediately precede the type character to respectively specify char types for d, i, u, o, x, and X. Characters following a percent sign that are not recognized as a format specification are treated as ordinary characters. For example, "%%" writes a single percent sign to the output stream. The flags field is a single character used to justify the output and to print +/- signs and blanks, decimal points, and octal and hexadecimal prefixes, as shown in the following table. Flag Description - Left justify the output in the specified field width. + Prefix the output value with a + or - sign if the output is a signed type. blank (' ') Prefix the output value with a blank if it is a signed positive value. Otherwise, no blank is prefixed. # Prefixes a non-zero output value with 0, 0x, or 0X when used with o, x, and X field types, respectively. When used with the e, E, f, g, and G field types, the # flag forces the output value to include a decimal point. The # flag is ignored in all other cases. The width field is a non-negative number that specifies the minimum number of characters printed. If the number of characters in the output value is less than width, blanks are added on the left (by default) or right (when the - flag is specified) to pad to the minimum width. If width is prefixed with a '0', zeros are padded instead of blanks. The width field never truncates the output. If the length of the output value exceeds the specified width, all characters are output. The width field may be an asterisk ('*'), in which case an intargument from the argument list provides thewidth value. Specifying a 'b' in front of the asterisk specifies that the argument is an unsigned char. The precision field is a non-negative number that specifies the number of characters to print, the number of significant digits, or the number of decimal places. Theprecision field can cause truncation or rounding of the output value in the case of a floating-point number as specified in the following table. Type Precision Field Meaning d,u,o,x,X The precision field specifies the minimum number of digits that are included in the output value. Digits are not truncated if the number of digits in the argument exceeds that defined in the precision field. If the number of digits in the argument is less than the precision field, the output value is padded on the left with zeros. f The precision field specifies the number of digits to the right of the decimal point. The last digit is rounded. e,E The precision field specifies the number of digits to the right of the decimal point. The last digit is rounded. g,G The precision field specifies the maximum number of significant digits in the output value. s The precision field specifies the maximum number of characters in the output value. Excess characters are not output. c,p The precision field has no effect on these field types. The precision field may be an asterisk ('*'), in which case an intargument from the argument list provides the value. Specifying a 'b' in front of the asterisk specifies that the argument is an unsigned char. Note You must ensure that the argument type matches that of the format specification. You may use type casts to ensure that the proper type is passed to printf. This function is implementation-specific and is based on the operation of the_getkey andputchar functions. These functions, as provided in the standard library, read and write characters using the microcontroller's serial port. Custom functions may use other I/O devices. The total number of bytes that may be passed to this function is limited due to the memory restrictions imposed by the 8051. A maximum of 15 bytes may be passed in SMALL or COMPACT model. A maximum of 40 bytes may be passed in LARGE model. Return Value The printf function returns the number of characters actually written to the output stream. See Also gets,printf517,puts,scanf,scanf517,sprintf,sprintf517,sscanf,sscanf517,vprintf,vsprintf Example #include void tst_printf (void) { char a = 1; int b = 12365; long c = 0x7FFFFFFF; unsigned char x = 'A'; unsigned int y = 54321; unsigned long z = 0x4A6F6E00; float f = 10.0; float g = 22.95;
Previous article:Immediate addressing, direct addressing, indirect addressing
Next article:About code, idata, xdata in C51
- Popular Resources
- Popular amplifiers
- Learn ARM development(16)
- Learn ARM development(17)
- Learn ARM development(18)
- Embedded system debugging simulation tool
- A small question that has been bothering me recently has finally been solved~~
- Learn ARM development (1)
- Learn ARM development (2)
- Learn ARM development (4)
- Learn ARM development (6)
Professor at Beihang University, dedicated to promoting microcontrollers and embedded systems for over 20 years.
- LED chemical incompatibility test to see which chemicals LEDs can be used with
- Application of ARM9 hardware coprocessor on WinCE embedded motherboard
- What are the key points for selecting rotor flowmeter?
- LM317 high power charger circuit
- A brief analysis of Embest's application and development of embedded medical devices
- Single-phase RC protection circuit
- stm32 PVD programmable voltage monitor
- Introduction and measurement of edge trigger and level trigger of 51 single chip microcomputer
- Improved design of Linux system software shell protection technology
- What to do if the ABB robot protection device stops
- CGD and Qorvo to jointly revolutionize motor control solutions
- CGD and Qorvo to jointly revolutionize motor control solutions
- Keysight Technologies FieldFox handheld analyzer with VDI spread spectrum module to achieve millimeter wave analysis function
- Infineon's PASCO2V15 XENSIV PAS CO2 5V Sensor Now Available at Mouser for Accurate CO2 Level Measurement
- Advanced gameplay, Harting takes your PCB board connection to a new level!
- Advanced gameplay, Harting takes your PCB board connection to a new level!
- A new chapter in Great Wall Motors R&D: solid-state battery technology leads the future
- Naxin Micro provides full-scenario GaN driver IC solutions
- Interpreting Huawei’s new solid-state battery patent, will it challenge CATL in 2030?
- Are pure electric/plug-in hybrid vehicles going crazy? A Chinese company has launched the world's first -40℃ dischargeable hybrid battery that is not afraid of cold
- Recently, I am doing an experiment on communication between DSP and AD5390. DSP controls AD5390 through SPI bus. I am not familiar with the core of AD5390.
- A new year and a new beginning. I wish you all a happy New Year!
- 【Project source code】 Analysis of blocking assignment and non-blocking assignment principles
- Please give a comprehensive analysis of the advantages and disadvantages of i.MX8QuadMAX and RK3399PRO
- Review Weekly Report 20211115: 1 day left to apply for Fudan Micro FM33LG0, Pingtou Ge smart voice, Anxinke PB-02 unboxing, etc.
- 【E840-DTU】MQTT sending and receiving test
- Who should I turn to for help when I need help with domestic FPCB manufacturers?
- uasyncio basic tutorial (English)
- Are there any netizens in our forum participating in the 2021 STM32 China Summit Hackathon 24-hour challenge?
- [RT-Thread Reading Notes] Week 3: Entering the World of RT-Thread - Threads, Clocks