Search code examples
c++avrcoutatmel

How to write a Cout<< Like print function for 16x2 LCD?


Development Environment

Controller: Atmega8
Language: C++ (-std=gnu++14 flag added )

IDE: atmel studio 7

Note: Most of the std:: libraries like ostream ,string ,cout, are not available with this minimal c++ support.

almost similar functionality has been implemented ,but the function call is different

printf1(<object>, ... ); 
 printf1(Lcd4bit2,"Val:",x,'=',5,"+",3.4);

I would like to change the code mentioned above ,something like this

LcdOut<<"Val:"<<m<<'='<<5<<3.4;, with minimal and efficient c++ code.

class LCD
{
  public:  

  void Write(const char* prnt)  
  {
     //16x2 LCD write code 
  }
};

    void LcdPrint(const char * val,LCD obj)
    {
        obj.Write(val);
    }
    
    void LcdPrint(char val,LCD obj)
    {
        char Str[2];
        sprintf(Str, "%c", val);
        obj.Write(Str);
    }
    
    void LcdPrint(double val,LCD obj)
    {
        char Str[16];
        sprintf(Str, "%f", val);
        obj.Write(Str);
    }
    
    void LcdPrint(int val,LCD obj)
    {
        char Str[16];
        sprintf(Str, "%d", val);
        obj.Write(Str);
    }
    
    template <typename T1,typename T0>
    void printf1(T1 Obj,T0 value) 
    {
        LcdPrint(value,Obj);
    }
    
    template <typename T1,typename T, typename... Ts>
    void printf1(T1 Obj,T value, Ts ... args) 
    {
        LcdPrint(value,Obj);
        printf1(Obj,args...);
    }
    
    int main(void)
    {
        char x ='m';
        Lcd4bit2.SetPos();  // set curser to 0,0 
        printf1(Lcd4bit2,"Val:",x,'=',5,"+",3.4);
    }

expected output

enter image description here


Solution

  • If you just want syntactic sugar for some basic output operations you could overload operator<< for the required datatypes. You could convert your overloads of LcdPrint to something like this:

    LCD &operator<<(LCD &lcd, double val)
    {
        char Str[16];
        sprintf(Str, "%f", val);
        lcd.Write(Str);
    
        return lcd;
    }
    
    LCD &operator<<(LCD &lcd, char val)
    {
        char Str[2];
        sprintf(Str, "%c", val);
        lcd.Write(Str);
    
        return lcd;    
    }
    
    // Overload for every required datatype
    

    Then you can chain them like this:

    LCD lcd;
    lcd << 0.5 << 'a';
    

    Not much different from what you have now, but the syntax looks more C++-ish. I'm also not sure if you need to move the cursor between between these calls, but I hope you get the idea.