Trying to figure out why my code isn't working as expected

int button = D0;

void setup() {
    pinMode(button,INPUT);
}

void loop() {
     if(button = false) {
           Spark.publish("door_open_test","true",60,PRIVATE);
     }
}

So trying to test something and feeling stupid. I made the simple code above with the intent of publishing an event to my dashboard when the button is pushed. Just getting basic functionality down before expanding. First I set the if to button = true and after flashing I saw 4 true’s publish to my dashboard. So I thought I had it backwards, and set it up as show here. Except now pushing the button has no effect. I am sure what I am missing is simple but at this time I am just needing to understand what I am missing.

Hi @Chainer

Two things:

  • Buttons need to be debounced–that is the physical button makes contact many times on-off-on-off before settling down to one state or the other. You can debounce using software or hardware. Try adding a pull-up resistor of say 4.7k ohm to +3.3V and a capacitor of 0.1 uF or so to ground to your input pin (D0 above). Then have the switch pull the pin low to ground when pressed.

  • There is a rate-limit on publishing of once per second with a burst of unto 4 allowed followed by a gap. This helps keep the cloud servers from being monopolized by any one user. This is why you saw 4 published events in the dashboard and then none–you triggered the rate-limiting.

And in this line

     if(button = false) {

you are not testing if the button pin got pulled low, but you set the value of the button variable to false (=0).

Rather do this

    if(digitalRead(button) == LOW) 
    // or shorter
    if(!digitalRead(button))