Search code examples
c++functionarduinoglobal-variables

Declare Global Object Inside Function C++


Suppose there is the following code to initialize an LCD display on an Arduino board:

#include <LiquidCrystal.h>

void LCDInit(){
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    lcd.begin(16, 2);
    lcd.setCursor(0, 0);
}

void LCDPrint(String data){
    lcd.print(data);
}

When I call LCDInit() it will initialize the LCD display connected to the Arduino.

If I try to print some text onto the LCD in a separate function (e.g. LCDPrint()), it won't work, because the lcd object is declared in a separate function, LCDInit().

My question is how can I make the lcd object global, so that referencing it in a separate function will work?

You can do this easily in Python with the global keyword, so how can it be done in C++?


Solution

  • #include <LiquidCrystal.h>
    #include <memory>
    
    std::unique_ptr<LiquidCrystal> lcd;
    
    void LCDInit(){
        lcd = std::make_unique<LiquidCrystal>(12, 11, 5, 4, 3, 2);
        lcd->begin(16, 2);
        lcd->setCursor(0, 0);
    }
    
    void LCDPrint(String data){
        lcd->print(data);
    }
    

    UPDATE: If you can't use std::unique_ptr, then just use new/delete manually, eg:

    #include <LiquidCrystal.h>
    
    LiquidCrystal* lcd = nullptr;
    
    void LCDInit(){
        lcd = new LiquidCrystal(12, 11, 5, 4, 3, 2);
        lcd->begin(16, 2);
        lcd->setCursor(0, 0);
    }
    
    void LCDCleanup(){
        delete lcd; lcd = nullptr;
    }
    
    void LCDPrint(String data){
        lcd->print(data);
    }