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

Const

        In our code we introduced a couple of new programming concepts that we can use along

        the way. We previously used variables to store our pin numbers in memory; however, in
        our firmware we will use something called a constant:


                   const int POT A0;

        This creates a spot of memory just like a variable does for an integer value called POT and
        stores the pin value A0. This seems like a variable but it isn’t—when using a constant, you

        cannot change or edit the value that is assigned to it, as the name suggests. This can be
        useful when you want to store a value in the memory and you know that this value should
        never be changed within the code. If you do change your code, then you will receive an

        error when verifying your sketch.




        map()

        Because the returned value of analogRead() is a value between 0 and 4095, you may find

        that you need to scale this range of values down into something a bit more manageable. In
        our case what we want to do is receive the value from the potentiometer and then write
        that value to the LED using analogWrite. Because the analogWrite function has a range

        from 0 to 255, we cannot simply write the value of the POT because it would be too high.
        For this we can use a function called map() to scale down the values to something we can
        use. We can scale the input value using the following code:


        int ledval = map(val, 0, 4095, 0, 255);


             The map() function is responsible for scaling one set of ranges to another. The input
        scale we use is from 0 to 4095, and the output scale is from 0 to 255. If we calculated this
        scaling range manually, it would become too complicated and sometimes difficult to work

        out; it could also return recurring values of an infinite nature.

             The syntax of map() is


                   map(input, inform, inTo, outFrom, outTo);

             The parameters for map() are


               input the input value to be scaled

               inform the first number in the input scale

               inTo the second number in the input scale

               outFrom the first number in the output scale

               outTo the second number in the output scale
   103   104   105   106   107   108   109   110   111   112   113