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

In  the  previous  code  examples  the  variables  were  declared  outside  both  the  setup  and
        loop functions. Those variables are always referred to as global variables because they

        can  easily  be  accessed  and  changed  from  either  the  setup  or  loop  functions.  In  our
        example code we declared a new variable within the loop function:


                   int state = digitalRead(pushbutton);


             When you call a variable within a block of code, it can only be accessed within that
        block.  This  is  known  as  a  local  variable  because  it  sits  within  a  function.  When  the
        program is running on the Photon and it finishes executing a particular block of code, any
        local variables within that block are automatically freed up in memory so they can be used

        for other variables in the next block of code.




        Debouncing

        When you press down on a push button, you would expect to just get a single change from

        1 to 0. However, in reality, that does not always occur. Sometimes when the contacts in the
        push  button  come  together,  they  bounce  when  you  release  the  button  and  create  static
        signals. So now a single button press has now become two or more presses, depending on

        the push-button switch. All of this happens in a split second—the total amount of time the
        button registers its press is less than 200 milliseconds. Most new tactile-type switches may
        not bounce at all; however, a very old switch may have a lot of bounce. Sometimes the
        bouncing  does  not  have  any  effect  on  the  outcome  of  our  sketch.  For  example,  in  our
        previous  sketch  we  detected  a  push-button  press,  which  then  turned  on  an  LED.

        Debouncing makes no difference to the outcome because when we release the switch, it
        will stabilize itself and the LED will switch off; this may take only a few milliseconds so
        we do not notice the debouncing effect.

             One situation where debouncing may cause your outcome to be different from what is

        expected is if we use a push-button switch to turn an LED on or off every time the switch
        is pressed. When you press the button, the LED comes on and stays on; when you press
        the button again, the LED turns off and stays off. If you had a button that bounced every
        time you pressed it, then the LED would be on or off based on whether you had an odd or

        even number of bounces. Using the same circuit as our previous sketch, try flashing the
        following program to your Photon:


        int ledpin = D7;
        int ledValue = LOW;


        void setup() {

        pinMode (D0, INPUT);
        pinMode (ledpin, OUTPUT);
        }
   96   97   98   99   100   101   102   103   104   105   106