PROGRAMMING - PRINTF()
Printing Out Data
Printing out data from a microcontroller is extremely
useful in robotics. You can use it for debugging your program, for use as a data logger,
or to have your robot simply communicate with someone or something else. This short tutorial
will give you sample code, and explain what everything means.
The most convenient way of writing to a computer through serial or to a LCD is
to use the formatted print utility printf(). If you have programmed in C++ before,
this is the equivalent of cout. Unlike most C functions this
function takes a variable number of parameters. The first two parameters are
always the output channel and the formatting string; these may then be followed
by variables or values of any type.
The % character is used within the string to indicate a variable value is to be
formatted and output.
Variables That Can Follow The % Character
When you output a variable, you must also define what variable type is being outputed.
This is very important, as for example a variable printed out as a signed long int will often not print out the
same as say the same variable printed out as an unsigned int.
Unsigned int (decimal)
Unsigned int (hex - lower case)
Unsigned int (hex - upper case)
Signed int (decimal)
Unsigned long int (decimal)
Unsigned long int (hex - lower case)
Unsigned long int (hex - upper case)
Signed long int (decimal)
End Of Line Control Characters
Sometimes you would like to control the spacing and positioning of text that is printed out.
To do this, you would add one of the commands below. I recommend just putting \n\r at the end
of all printf() commands.
go to new line
Examples of printf():
printf("squirels are cute\n\rpikachu is cuter\n\r");
printf("the answer is %u", answer);
printf("the answer is %u and %f", answer, float(answer));
printf("3 + 4 = %u", (3+4));
printf("%f, %u\n\r", (10/3), answer);
printf("the sensor value is %lu", analog(1));