Help,how to use a variable outside of its routine?

Hi,

New to Arduino!

I want to use the variable tempC outside of its routine? but its local to routine, how do i use it outside of its routine?

Example

void printTemperature(DeviceAddress deviceAddress)
{
float tempC = sensors.getTempC(deviceAddress);
Serial.print("Temp C: ");
Serial.print(tempC);
Serial.print(" Temp F: ");
Serial.print(DallasTemperature::toFahrenheit(tempC));
}

Regards

Gary

Declare it outside setup as a global variable.

Then you can read/write to it in any part of your code.

Mowcius

Hi Mowcius

Thanks for that quick reply, i knew it would be something simple!

Regards

Gary

No worries.

The reason why you normally declare a variable in a routine like that is to keep the RAM usage down.
If you have a variable declared through the whole sketch then the RAM is used through the whole sketch rather than just in its routine.

Mowcius

One problem with making tempC global has to do with knowing where it is modified. A function with a name like printTemperature is not expected to alter the value of the variable it is supposed to be printing.

If you make tempC global, you should consider renaming the function to indicate that it does alter the value in tempC, to something like getAndPrintTemp().

You could also make printTemperature return a value, and make it return the value that is stored in the local variable tempC. But, again, the name of the function does not reflect what it really does.

Hi Thanks to both of you that has really helped a lot

Regards

Gary