11 years, 5 months ago.

how do I make printf use my putc routine ?

Hi,

I'm new to c++ and i'm struggling with the concept of libraries and classes so I'm trying to keep things simple, by avoiding them.

How do i make the built in printf function use my own implementation of a putc routine (not in a library, just a function). I have an LCD screen that my own routines use fine, but I'd liek to uise the more advanced text formatting of printf and I can't make it use my putc routine...

Any help appreciated.

Thanks,

Peter

3 Answers

11 years, 5 months ago.

This might not be answering the question but if you want to keep things simple use sprintf to write to a character buffer and then call your custom putc function on each character in the buffer up to the zero character at the end. Like this:

int appleCount = 10;
char buf[ 30 ];
sprintf( buf, "I have %d apples.\r\n", appleCount );
char *ptr = buf;
while( *ptr != (char)0 ) {
    myPutc( *ptr++ );
}

Make sure you use a big enough character array to hold the entire message.

Accepted Answer

Thats exactly how I was solving the 'issue' in the short term and it works fine, but its just a little awkward. I'd hoped for something like the way that the libraries can simply define a putch function and it auto-magically gets used by printf.

posted by Peter Wilson 19 Nov 2012
11 years, 5 months ago.

if you look through some of the examples in the cookbook and the forums. there are examples but I think you just write your own putc block.

apologies - I only have phone today.

Ceri

11 years, 5 months ago.

You can use the printf() in your own code by creating a class thas inherits from 'Stream' and implements putc().

Have a look at the example TextLCD library:

class TextLCD : public Stream {

...
}

The link to .h is here: https://mbed.org/users/simon/code/TextLCD/docs/44f34c09bd37//TextLCD_8h_source.html

The link to .cpp is here: https://mbed.org/users/simon/code/TextLCD/docs/44f34c09bd37//TextLCD_8cpp_source.html

The lib is described here: https://mbed.org/users/simon/code/TextLCD/docs/44f34c09bd37//classTextLCD.html#a98631211a4a8aee62f572375d5b637be

OK... technically I'm clueless about c++ and when I look at the .h and .cpp files I am totally out of my depth, not a clue what is going on there, but I've seen a few implementations that do it this way. I backed away from libraries since I was challenged with using two libraries that both wanted to control the same SPI device with different protocols and simply wouldn't co-exist peacefully, i stripped the code into my main .c and things work fine, but the printf problem then raises its head... for the moment I'm getting by with sprintf and a putch of the resulting strings... its OK, not ideal but it works.

posted by Peter Wilson 19 Nov 2012