Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
12 years 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
12 years 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.
12 years 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
12 years 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 19 Nov 2012