Go Down

Topic: Delcaring a Global Object ? (Read 1 time) previous topic - next topic

A.Selby

Feb 23, 2009, 01:24 am Last Edit: Feb 23, 2009, 02:37 am by Anthony.Selby Reason: 1
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

halley


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

Code: [Select]
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: [Select]
#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: [Select]
void setup()
{
   SomeClass myInstance = SomeClass(someParams);
   myInstance.doSomething();
   some_other_func(&myInstance);
}

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


Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy