Arduino Forum upgrade scheduled for Monday, October 20th, 11am-4pm (CEST). Sorry for the inconvenience!
Pages: [1]   Go Down
Author Topic: How to expose instance to be used by another class  (Read 553 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Sr. Member
****
Karma: 8
Posts: 296
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

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.
Logged

Ayer, Massachusetts, USA
Offline Offline
Edison Member
*
Karma: 54
Posts: 1857
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
class DS1307
{
    // ....
}

extern DS1307 RTC;

and it file.cpp you would have:

Code:
// 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.
« Last Edit: March 19, 2013, 10:12:48 pm by MichaelMeissner » Logged

0
Offline Offline
Sr. Member
****
Karma: 8
Posts: 296
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

0
Offline Offline
Sr. Member
****
Karma: 8
Posts: 296
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
#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.
« Last Edit: March 23, 2013, 03:57:40 pm by mistergreen » Logged

Pages: [1]   Go Up
Arduino Forum upgrade scheduled for Monday, October 20th, 11am-4pm (CEST). Sorry for the inconvenience!
Jump to: