# Basic IF statement errors

**URL:** <https://community.particle.io/t/basic-if-statement-errors/33681>\
**Category:** Getting Started\
**Created:** [June 11, 2017, 4:06pm UTC](https://community.particle.io/t/basic-if-statement-errors/33681 "2017-06-11T16:06:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Pearseco](https://avatars.discourse-cdn.com/v4/letter/p/d07c76/32.png) [@Pearseco](https://community.particle.io/u/Pearseco)\
**Post date:** [June 11, 2017, 4:06pm UTC](https://community.particle.io/t/basic-if-statement-errors/33681/1 "2017-06-11T16:06:55Z")

</div>

I seam to be having a fundamental error with the code below;

```cpp
int bInput1 = D0;
int bBoardLed = D7;

void setup() {
    pinMode(bInput1, INPUT);
    pinMode(bBoardLed, OUTPUT);
    digitalWrite(bBoardLed, LOW);
}

void loop() {
    if (digitalRead(bInput1) == HIGH) { 
        Particle.publish("#######","on");
        digitalWrite(bBoardLed, HIGH);
// delay(1000);
    }
    else if (digitalRead(bInput1) == LOW) {
        Particle.publish("#######","off");
        digitalWrite(bBoardLed, LOW);
// delay(1000);
    }
    else {
        
    }

```

When running, the local LED will toggle on operating the input from a pushbutton, but the Publish function gives a return value of “off”.  
But if I introduce the time delay of 1s to each statement, the code cycles through, toggling the local LED and the published result also toggles.  
If during this “delayed” code I operate the button (pulldown to gnd) the LED and the published result stay off. returning to cycling upon release.

Thanks

---

<div class="post-metadata">

**Author:** ![ScruffR](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/scruffr/32/6952_2.png) [@ScruffR](https://community.particle.io/u/ScruffR)\
**Post date:** [June 11, 2017, 4:25pm UTC](https://community.particle.io/t/basic-if-statement-errors/33681/2 "2017-06-11T16:25:10Z")

</div>

First, for a switch to read correctly when not closed, you need to use pull-resistors (e.g. INPUT\_PULLUP, INPUT\_PULLDOWN or an external resistor) and  
second, you should only `digitalRead()` once and store the value and  
third there is no third option for `digitalRead()`, so the final `else` block is superfluous and  
fourth you may want to only act upon change (i.e. store and compare the previous state and only act on `(prevState != curState)`)
