Pages: [1]   Go Down
Author Topic: Delcaring a Global Object ?  (Read 909 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 28
I need more space !!! Everyone is closing in on me
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hey everyone,

  I have a arduino with the ethernet shield, Its been working ok ... expect for the power/reset problem but I'm going to run to the store tomorrow to see if i can fix that. On to my problem, I've been making a basic web server and everything goes fine if I stay in the main loop function (which is where I set the client to the server.available) but when I move to a separate function that needs to talk to the client ... I get an out of scope error, which I expect but what I don't know how to do is declare the uninitialized client so it will be global to all my functions / subroutines. I tried re-declaring the client in those functions but its not the most reliable thing in the world and most times I end up having to reset the arduino because it keeps waiting for the client to be available. If anyone knows if this is possible ...

Thanks

*Update*

   I also tried passing the client object to the next subroutine and I available is always nothing until it moves back to the calling function where the data is waiting and gets processed by the first routine ( I don't know if the arduino supports passing objects by reference, anyone know how to do that?)

  any ideas would be helpful
« Last Edit: February 22, 2009, 08:37:35 pm by Anthony.Selby » Logged

Connecticut, US
Offline Offline
Edison Member
*
Karma: 2
Posts: 1036
Whatduino
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset


Declare the instance as a global.  I have no idea what class you're working with, so I'm making up names.

Code:
SomeClass myInstance = SomeClass(someParams);

void setup()
{
    myInstance.doSomething();
}

void loop()
{
    some_other_func();
}

void some_other_func()
{
    myInstance.doSomething();
}

Alternatively, if you want to control WHEN it's constructed, declare a global pointer to the instance, and make the instance when you're ready.

Code:
#include <stdlib.h> // for malloc and free
void* operator new(size_t size) { return malloc(size); }
void operator delete(void* ptr) { free(ptr); }

SomeClass* ptrToMyInstance = NULL;

void setup()
{
    // get ready
    ptrToMyInstance = new SomeClass(someParams);
    ptrToMyInstance->doSomething();
}

void loop()
{
    some_other_func();
}

void some_other_func()
{
    ptrToMyInstance->doSomething();
}

And finally, if you don't want to include the overhead of defining new/delete, or you want to pass addresses to functions reliably,

Code:
void setup()
{
    SomeClass myInstance = SomeClass(someParams);
    myInstance.doSomething();
    some_other_func(&myInstance);
}

void some_other_func(SomeClass* ptrToMyInstance)
{
    ptrToMyInstance->doSomething();
}
Logged

Pages: [1]   Go Up
Jump to: