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

Commands


        The C language on the Photon has a number of built-in commands. In this section we will
        explore some of these commands and see how they can be used in our firmware.






        The if Statement


        In our examples so far we have assumed that your lines of programming will be executed
        in order one after the other. But what if we don’t want to do this and we want to execute a
        block of code when something happens in the code. For this we can use an if statement,

        which  is  used  in  conjunction  with  a  comparison  operator,  and  test  whether  a  certain
        condition has been reached, such as an input being higher or lower than a certain number.
        The formatting for an if statement is as follows:


                   if (variable > 50)

                   {
                   //Write your code here
                   }


             The program tests to see if the variable is greater than 50. If it is, then the program
        takes  a  particular  action  and  executes  the  code  in  between  the  curly  braces.  If  the
        condition is not reached, then the program skips over this section and moves on to the
        next. Also, the curly braces may be omitted after an if statement; if this is done, then the

        next line of code becomes the only conditional statement, as shown in the next example:


        if (x > 50) digitalWrite(LEDpin, HIGH);
                   if (x > 50)
                   digitalWrite(LEDpin, HIGH);
                   if (x > 50) { digitalWrite(LEDpin, HIGH); }

                   if (x > 50) {
                              digitalWrite(ledPin1, HIGH);
                              digitalWrite(ledPin2, HIGH);
                   }


             All  of  the  examples  are  correct  for  using  an  if  statement.  Note  that  we  used  the
        symbol >, which means “more than.” It is one example of what are called comparison
        operators. These operators can be found in Table 3.2.
   57   58   59   60   61   62   63   64   65   66   67