Page 57 - Programming the Photon Getting Started With the Internet of Things
P. 57

delay(1000);
            digitalWrite(LED, LOW);

            delay(1000);
        }

        The setup function in our sketch calls one built-in function called pinMode. The function

        pinMode is used to set a particular pin to be either an input or an output. So with this in
        mind it is clear that we need to initially set our LED to be an output, which will also let us
        use the function digitalWrite later on. The pinMode is always used in the setup function

        because we only need to set the pin mode once in our sketch. The program would still
        work if you called this in the loop function, but for best coding practices it is always best

        to keep things that you call once in the setup function—then you know where everything
        is that you only call once.




        Variables


        A variable is a place in the memory to store a piece of data. It has a name, a value, and a
        type. For example, the following statement declares the pin number:


        int pin = D0;

        This code creates a variable called pin whose value is D0, and its type is int. Later on in

        your program you can refer to this variable by its name, at which point its value will be
        looked up and used. For example:


        pinMode(pin, OUTPUT);


        It is the value of the pin that will be passed into the pinMode() function. In this particular
        case you don’t actually need to use a variable; this statement would work just as well if
        you referenced the pin number directly:


        pinMode(D0, OUTPUT);


        The advantage of a variable in this case is that you only need to specify the actual number
        of the pin once, but it has a huge advantage in that you can use this more than once in your
        code. When naming your variable you can also use a descriptive name, which will make
        the significance of the variable clearer (e.g., a program controlling some LEDs might have
        variables called redPin, GreenPin, etc.).


             A variable has other advantages over a value like a number. You can change the value
        of a variable using an assignment (indicated by an equal sign). For example:


        pin = D1;

        This  will  change  the  value  of  the  variable  to  D1.  You  can  see  that  we  don’t  actually
   52   53   54   55   56   57   58   59   60   61   62