The printf() Function
printf("ControlString", arg1, …, argN);
- Prints ControlString to Standard Output (the terminal on a PC, typicaly a UART on microcontrollers)
- The MPLAB® X IDE Simulator uses the UART1 Output window to display text written to the UART using printf().
- All comma separated parameters are optional except for ControlString
- The argument parameters (arg1 … argN above) can be variables or other data to be embedded within ControlString
- Placeholders are put in ControlString to indicate where value of an argument parameter should be inserted
- Placeholders indicate position in string and format to be used in printing data embedded within ControlString
- printf() requires huge amount of memory. Best used for debugging only unless you need all of its functionality.
The code above would produce the following output:
a = 5
b = 10
Where "_" indicates the position of the cursor at the end of the operation.
- The code in Example 1 defines two variables: a and b.
- We want to print their values as part of a string that indicates which value goes with which variable.
- The ControlString is "a = %d\nb = %d\n".
- Each %d is a placeholder that indicates where one of the arguments should be inserted and how it should be formatted when printed.
- The value of a is inserted at the position of the first %d and the value of b is inserted at the position of the second %d.
- The d in the %d is called a format specifier or a conversion character and indicates that the value should be printed as a signed decimal integer.
- The \n is an escape sequence indicating that a new line should be inserted, causing the cursor to go down to the next line before continuing to print.
|%s||String (all characters until '\0')|
|%d||Signed decimal integer|
|%o||Unsigned octal integer|
|%u||Unsigned decimal integer|
|%x||Unsigned hexadecimal integer with lower case digits (e.g. 1a5e)|
|%X||Same as %x but with upper case digits (e.g. 1A5E)|
|%f||Signed decimal value (floating point)|
|%e||Signed decimal value with exponent (e.g. 1.26e-5)|
|%E||Same as %e but uses upper case E for exponent (e.g. 1.26E-5)|
|%g||Same as %e or %f, depending on size and precision of value|
|%G||Same as %g but will use capital E for exponent|