How to get printf to work in a new display driver class

If you use Stream as a base class in a new class to drive an LCD display, the class will inherit the C++ printf member function. You can overload the virtual_putc function and get lcd.printf(…) to work with a default text size. Printf code eventually calls the function_putc to print out each individual character.
It goes something like this:

//New class setup to drive a display
class NEWLCDCLASS : public Stream //use Stream base class
{
……
// lots of code for the new LCD class - not shown here to keep it simple
.....
//and add this to the end of the class
protected
    //used by printf - supply a new _putc virtual function for the new device
    virtual int _putc(int c) {
        myLCDputc(c); //your new LCD put to print an ASCII character on LCD
        return 0;
    };
//assuming no reads from LCD
    virtual int _getc() {
        return -1;
    }



With that setup, any myLCD.printf() with variables and format strings will work just like printf().

http://developer.mbed.org/users/simon/code/TextLCD/file/308d188a2d3a/TextLCD.h

The library above has an example of this. I noticed Simon Ford did this in his earlier Text and Nokia LCD code. It does come in very handy for quicker coding, since programs can use printf’s easy to use features to print out program variables. Your new myLCDputc might need some extra code to handle \n or \r in a printf and keep track of the cursor position.


Please log in to post comments.