Go Down

Topic: How to expose instance to be used by another class (Read 575 times) previous topic - next topic

mistergreen

Hi,
I have a RTC class that has an extern instance.
Code: [Select]


class DS1307
{
......
}
extern DS1307 RTC;


And I have another class wanting to get the time from this class by calling RTC.getTime() and so on. I found out this is not enough, I'd get an "'RTC' was not declared in this scope" error.
So how do I make it so RTC.getTime() can be called from anywhere from another class to the arduino sketch?

Maybe make getTime() a static method and not do an instance RTC?

thanks.

MichaelMeissner

#1
Mar 20, 2013, 04:09 am Last Edit: Mar 20, 2013, 04:12 am by MichaelMeissner Reason: 1
If you are moving things to separate libraries, you need to include the definitions for class DS1307 and RTC so that the library can see it.  Typically this would be done in a common include file.

In file.h you would have:

Code: [Select]

class DS1307
{
   // ....
}

extern DS1307 RTC;


and it file.cpp you would have:

Code: [Select]

// Define RTC
DS1307 RTC;


Note, when you have .cpp files, you need to make sure you have the prototypes for the functions declared before they are used, since this is something the IDE does behind your back for .ino/.pde files.

At the advanced C++ level, there are the concepts of public, private, and friend, superclasses, subclasses that can be used, but that is probably a more complex task.

mistergreen

Thanks. That did it. I just needed to #include the DS1307.h.

I'm already extending 2 other classes. I thought doing this way would be easier since the DS1307 can have a constructor and can be accessed on the main sketch too.

mistergreen

#3
Mar 23, 2013, 09:50 pm Last Edit: Mar 23, 2013, 09:57 pm by mistergreen Reason: 1
Hi, this compiles fine but crashes the arduino when it starts up. Sorry, no error message except garbled text in the serial monitor.
I'm using the extern RTC instance in another class like so.

Device.cpp
Code: [Select]

#include "../DS1307new/DS1307new.h"

void Device::checkTimedEvent() {
 RTC.getTime();
 //.... and so on
}


The arduino is fine when I comment out the RTC.. I guess this shouldn't be done.

Not sure what should be done. I guess I'll turn the RTC.getTime() into a static function and see.

Go Up