2

I want to make a class in cpp for arduino uno that writes on a display. I'm using the LiquidCrystal_I2C library but I can't use it in my class. I know how to do it without a class, but right now I want to build a class and I cant get it to work.

My .h file:

// WriteDisplay.h

#ifndef _WRITEDISPLAY_h
#define _WRITEDISPLAY_h

#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
    #include "WProgram.h"
#endif
#include <Wire/Wire.h>
#include <LiquidCrystal_I2C2004V1/LiquidCrystal_I2C.h>

class WriteDisplayClass
{
 public:
    WriteDisplayClass();
    void write(String text);
 private:
    LiquidCrystal_I2C lcd(0x27,20,4);
};

extern WriteDisplayClass WriteDisplay;

#endif

My .cpp:

#include "WriteDisplay.h"

WriteDisplayClass::WriteDisplayClass()
{
    lcd.init();
    lcd.backlight();
    lcd.setCursor(0, 0);
}

WriteDisplayClass::write(String text)
{
    lcd.clear();
    lcd.print(text);
}


WriteDisplayClass WriteDisplay;

My .ino:

#include "WriteDisplay.h"

WriteDisplayClass wdc;
void setup()
{
    wdc.write("Hello World");
}

void loop()
{
}

I'm using AtmelStudio with Visual Micro. I'm getting it to work when I'm only using my .ino-file, but I can't do the same thing in cpp. I'm getting errors that LiquidCrystal_I2C.h can't be found and stuff like that. How should I do to get it to work the way I want it to? Or is it even possible?

Thanks for answer.

2 Answers2

0

Sorry I misread the question the first time.

To use libraries in the .cpp file of an Arduino sketch you must also include them in the master .ino file. They are only compiled if found in the .ino

You can add the includes manually or use the "Project>Add/Import Sketch Library" menu item which will add them to the .ino for you.

Visual Micro
  • 1,561
  • 13
  • 26
0

Based on this post here the problem with your code is related the class being instantiated as global. The problem comes that the compiler doesn't guarantee the order of global variables processing, so in order to guarantee that the object concerning the display is executed lastly after all the library ones, you have to instantiate it in the setup() function!

The solution to your .ino code is to set a global pointer and then you assign the object inside the setup() function, like so:

#include "WriteDisplay.h"

WriteDisplayClass *wdc;

void setup()
{
    wdc = new WriteDisplayClass();
    wdc->write("Hello World");
}

void loop()
{
}
Rui Monteiro
  • 181
  • 1
  • 7