I need some clarification as I think i read this somewhere but want to make sure.
The question, can global variables that are called within one function be called by another and pull it's value? I have tested it with a simple voltage query program on A0 by calling 'getcv' that uses a global variable (voltage) that is declared outside of the functions. But when the program returns from the function it does not keep the variables value.
I have verified the voltage variable does get the correct value within the getcv function as 5v, but when it comes back calling only returns a 0 (zero).
Example code:
int voltage;
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
getcv();
Serial.println(voltage);
}
void getcv(){
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}
that worked, but of course without the float you get no decimal value. I fixed that by adding float voltage(); as a global variable and removing 'float' from the function.
corrected code:
float voltage;
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
getcv();
Serial.println(voltage);
}
// the loop routine runs over and over again forever:
void loop() {
}
void getcv(){
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}
Nah. In this case, the righteous thing to do is to return the value from the function.
You should separate the "getting" and the "printing" though... 'getcv' would normally name a function that returns a value. 'printcv' would print it.
float getcv(){
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
return voltage;
}
...
Serial.println(getcv());
Pointers are cool but the suggestion to use them in this situation is misguided. They're simply not needed, and would only complicate things unnecessarily.