Page 58 - Programming the Photon Getting Started With the Internet of Things
P. 58
specify the type of variable when changing the value—only the name of the variable and
the variable type stay constant. Remember that you have to declare a variable before you
can assign a value to it. You can, of course, make a copy of a variable within your code if
needed. When you change the value of one variable, it does not affect the value in another.
This is useful for when you change the value of a variable but also want to keep the
original value in case you need to go back to it. For example:
int pin = D0;
int pin2 = pin;
pin = D1
Only the variable pin would have changed to D1, and pin2 would remain the same (D0).
If you try changing the value of a variable before you have declared the variable, you
will receive an error in your code when trying to compile it: “error: pin was not declared
in the scope.” (Scope refers to the part of your program where the variable can be used.)
This is determined by where you declare it. For example, if you want to be able to use
your variable anywhere within your program, then you must declare the variable at the top
of the program. This is known as a global variable. Here is an example of declaring a
global variable:
int pin D0;
void setup() {
pinMode(pin, OUTPUT);
{
void loop() {
digitalWrite(pin, HIGH);
}
As you can see in the example, pin is used in both the setup and loop functions. Both
functions are referring to the same variable; therefore, it must be set as a global variable. If
you only need to use a variable in a single function, then you declare it there, in which
case its scope will be limited to that particular function. For example:
void setup() {
int pin D0;
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);
}
In this example the variable pin can only be used inside the setup function. If you try to
use it within the loop function, you will receive an error in your program. You may be
wondering why we don’t simply declare all variables as global variables at the start of the
program. Well, it makes it easier to find out what has happened to the value of the
variable. If you remember that when we use a global variable the value can be changed