Go Down

Topic: Getting string value out of function (Read 3352 times) previous topic - next topic

Tissy

I have been used to programming MCUs in Basic, so transferring over to C++ has not been an easy journey.

I have a piece of code where I am trying to get the value of a string back into the main loop.

In basic this would be easy with a Gosub command, but i cannot figure it out in Arduino.

My structure looks like this and it is the content of the 'message' string that I am trying to get back into the main loop.

I have tried various 'return' functions without success.

Is anybody able to assist please so I can goto bed :)

Many thanks.

Code: [Select]

void loop()
{
  temperature();          //  Calls Temperature function
 
  ...lots more code
}

void temperature()
{
  ...lots more code

     String message;
     
     message = inString.substring(startCommand+1, stopCommand);

     Serial.println(message);
}

Delta_G

Make the function return a string instead of void and put

return message;

at the end.

Then in the loop, create a variable to hold the string and use the function to get it.

String temperature_message = Temerature();


Alternatively, you could move the line that declares message:

String message;

out to global scope and then it would be visible by the whole program and you just call the void temperature() function to update it. 

PaulS

Quote
Make the function return a string instead of void and put

return message;

at the end.

Then in the loop, create a variable to hold the string and use the function to get it.

String temperature_message = Temerature();

That absolutely will NOT work. When temperature ends, the message variable goes out of scope, which means that the memory it was using is available to be reused. Returning a pointer to that space is not a great idea.

What you do need to do is pass the function a reference to a String object that you want it to write to.
Code: [Select]

void temperature(String &dest)
{
   dest = inString.substring(startCommand+1, stopCommand);
}


Then call the function:
Code: [Select]
void loop()
{
   String junk;
   temperature(junk);

   Serial.print("temperature returned: ");
   Serial.println(junk);
}


One thing that will trip you up is that the IDE fails to create function prototypes for functions that use reference arguments. You will either need to define the function before any calls to the function or create the function prototype yourself.

On the other hand, since everything else that temperature() deals with is a global variable, it doesn't really make sense to try to make it deal with local variables, too.

Go Up