Basic IF statement errors

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

int bInput1 = D0;
int bBoardLed = D7;

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

void loop() {
    if (digitalRead(bInput1) == HIGH) { 
        digitalWrite(bBoardLed, HIGH);
//        delay(1000);
    else if (digitalRead(bInput1) == LOW) {
        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.


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))

1 Like