Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

c++ - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...