3.4.8 How Do I Use Printf to Send Text to a Peripheral?
The printf()
function does two things:
- Formats text based on the format string and conversion specifiers you specify.
- Sends (prints) this formatted text to a destination (or stream).
See 5.11.2 Smart IO Routines and the Microchip Unified Standard Library Reference Guide for more information.
The printf()
function performs all the formatting; then calls a helper
function called putch()
, to send each byte of the formatted text. By
customizing the putch()
function you can have printf()
send data to any peripheral or location. You can choose the printf()
output go to an LCD, SPI module, or USART for example.
A stub for the putch()
function can be found in the
compiler’s pic/sources directory. Copy it into your project, then
modify it to send the single byte parameter passed to it to the required destination.
Before you can use printf()
, peripherals that you use will need to be
initialized in the usual way. Here is an example of putch()
for a USART
on a mid-range PIC device.
void putch(char data) {
while( ! TXIF) // check buffer
continue; // wait till ready
TXREG = data; // send data
}
You can get printf()
to send to one of several
destinations by using a global variable to indicate your choice. Have the
putch()
function send the byte to one of several destinations based
on the contents of this variable.