#include <stdio.h>
Remember to include a terminating “\n” in your printf – stdout doesn’t flush until it encounters one by default!!!!
If printf still doesn’t occur you may need fflush(stdout); or consider using std::cout instead
printf("Hello world!\n");
printf("%i bytes read : %s\n", rx_length, rx_buffer);
printf("data_h: %02X\n", sensor_data_h);
printf format codes
bool %d
int %d
int %i
int8_t %hhd
uint8_t %hhu
int16_t %hd
uint16_t %hu
int32_t %ld
uint32_t %lu
int64_t %lld
uint64_t %llu
char[] %s
float %f (Decimal floating point)
float %.3f (3 represents the number of digits after the decimal separator)
float %e (Scientific notation (mantissa/exponent), lowercase)
float %g (Use the shortest representation: %e or %f)
double %lf (up to 6 digits of precision using standard decimal notation, without any trailing zeros)
double %lg (up to 6 digits of precision which can use scientific notation if its shorter)
//Displaying hex:
uin16_t 0x%04X (display 4 characters of hex)
//Alternative bool
printf("%s", x ? "true" : "false");
d or i – int, decimal (base ten) number
x or X – int, hexadecimal number. Also “%02x” to specify length of digits
ld – long, decimal number (‘l’ can also be applied to any of the above to change the type from ‘int’ to ‘long’)
u – unsigned, decimal number
lu – unsigned long, decimal number
llu – unsigned long long, decimal number (uint64_t)
c – char, single character
s – char pointer, string
f – float, number with six digits of precision
g – float, number with up to six digits of precision
e – float, number with up to six digits of precision, scientific notation
lf – double, number with six digits of precision
lg – double, number with up to six digits of precision
le – double, number with up to six digits of precision, scientific notation
Including values examples
Hex values
//Include a 2 digit HEX value "%02"
printf("MyValue: 0x%02X\n", (uint16_t)SwitchInputs);
//Include a 4 digit HEX value "%04"
printf("MyValue: 0x%04X\n", (uint16_t)SwitchInputs);
Int values
//Force to 2 digits
printf("MyValue: %02i\n", (uint16_t)TimeHours);
Result of an operation
printf((err != ESP_OK) ? "Failed!\n" : "Done\n");
printf in a multi-thread environment
Watch out for clashes causing bugs! This can happen with irq’s using printf, different threads using it, etc.
Using a semaphore to protect
This is one option to stop clahses, e.g.
#include "semphr.h"
//Create semphore
SemaphoreHandle_t print_semaphore = NULL;
print_semaphore = xSemaphoreCreateMutex();
//Use sempahore
xSemaphoreTake(print_semaphore, portMAX_DELAY);
printf("Something");
printf("Something");
xSemaphoreGive(print_semaphore);