In the last lesson we said that local variables are preferable to global variables, so this week let's look at how we can pass the value from a local variable to another procedure using "parameters".
A parameter is basically an input to a routine. We have seen them already, in the built in map() function. This function requires 5 inputs, the variable you want to scale, the current minimum value, the current maximum value, the new minimum value, and the new maximum value, and it returns the newly scaled integer.
We can write our own routines that take parameters, and here is an example using the last program as a base.
Re-save the program as Ex6_Parameters, and adjust it so it looks like this:
const int pot = A1;
const int water = 5;
void setup() {
//put your setup code here, to run once:
pinMode(pot, INPUT);
pinMode(water, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int value = analogRead(pot);
checkLevel(value);
delay(1000);
}
void checkLevel(int paramvalue){
if(paramvalue>200 && paramvalue<800){
digitalWrite(water, HIGH);
}
else{
digitalWrite(water, LOW);
}
}
You should notice this is a lot like the last program, but we have removed the global variable "value" and replaced it with a local variable within the loop(). This variable cannot be altered or read by any other routine except loop() itself.
As a result, when we want checkLevel() to run a test on the number in this variable, we must "pass" the number to the checkLevel() routine as a parameter.
N.B. When we use parameters like this, we are only passing the actual number in the variable at that moment in time, not access to the variable.
We have told the checkLevel() procedure to expect an integer and to store it in a local variable called "paramvalue". (Notice, as they are both local variables, I could have called them both "value", but they would still be different. This is highly confusing, so I advise you to use different names for each local variable so you never get confused about which you are talking about.)
What we have achieved here is the separation of all variables into local form. This means I cannot accidentally overwrite the value in any of them from another routine. This method of passing values between routines as parameters is fundamental to good coding practice.
Save the program before you move on.