For printing basic messages on a console, we can use the printk()
method. The syntax printk()
is similar to the standard printf()
in C, you can provide either a string literal or a format string followed by one or more variables to be printed. However, printk()
is a less advanced function that only supports a subset of the features that printf()
does, making it optimized for embedded development.
A basic set of specifiers are supported:
%d
, %i
and its subcategories %u
and its subcategories%x
(%X
is treated as %x
)%p
%s
%c
%%
\n
\r
Field width (with or without leading zeroes) is supported. Length attributes h
, hh
, l
, ll
and z
are supported. However, integral values with lld
and lli
are only printed if they fit in a long
, otherwise ERR
is printed. Full 64-bit values may be printed with llx
. Flags and precision attributes (float and double) are not supported by default, but can be enabled manually, which we will cover in Lesson 6.
For example, the following line will print the string Button 1 was pressed!
on the console (including a new line and carriage return).
printk("Button 1 was pressed!\n\r");
CWhile this line will print the formatted string The value of x is 44
on the console (including a new line and carriage return).
int x = 44;
printk("The value of x is %d\n\r",x);
CUsing printk()
is straightforward, all you have to do is :
1. Include the console drivers.
This is done by enabling the configuration option CONFIG_CONSOLE
in the application configuration file. This step is not necessary if it is set in the board configuration file.
2. Select the console.
There are a few options available, such as the UART console (CONFIG_UART_CONSOLE
) and RTT console (CONFIG_RTT_CONSOLE
). In this lesson, we will focus on the UART console, which can easily be captured using a serial terminal program like the built-in serial terminal in VS Code. The default console set in the board configuration file is the UART console. This step is not necessary if it is set in the board configuration file.
3. Include the header file <zephyr/sys/printk.h>
in your application source code.
In exercise 1, we will practice using the printk()
function.
The output of the printk()
is not deferred, meaning the output is sent immediately to the console without any mutual exclusion or buffering. This is also known as synchronous logging, in-place logging, or blocking logging. Logs are sent immediately as they are issued, and printk()
will not return until all bytes of the message are sent. This limits the use of this function in time-critical applications.