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

void loop() {

            if (digitalRead(D0) == HIGH) {
                ledValue = ! ledValue;
                digitalWrite(ledpin, ledValue);
            }
        }


        Press the push button a few times and see what happens. You may notice that when you
        push the button that the LED may not turn on or off as it should, but when you push it a

        few more times, it does turn on or off. As previously explained, this is a perfect example
        of  how  debouncing  occurs.  Try  loading  the  following  sketch  with  the  addition  of  the
        highlighted code in bold:


        int ledpin = D0;
        int ledValue = LOW;



        void setup() {
        pinMode (D1, INPUT);
        pinMode (ledpin, OUTPUT);
        }



        void loop() {
            if (digitalRead(D1) == HIGH) {

                ledValue = ! ledValue;
                digitalWrite(ledpin, ledValue);
                delay (200);
            }
        }


             Press the push button again a few times—notice anything different? This time it works
        fine after inserting a short delay into the program. This is because as soon as the program
        registers the first push of the switch, it delays the program before it checks again just in

        case there is another bounce on the switch.

             Sometimes when writing your code you may need to reverse a value from HIGH to
        LOW. You can do this with Boolean logic using the ! or not operator:


        ledValue = ! ledValue;


        In your program you used this to reverse the value of the LED. You set the LED value as a
        global variable at the start, which was LOW, so the equation is “ledValue is equal to not
        LOW,” which becomes HIGH. So when we use digitalWrite your value used to light up

        the LED is HIGH.
   97   98   99   100   101   102   103   104   105   106   107