push buttons / only 1 state



  • Ok, so I am still very very new to this. I made what I am trying to do work, but I am curious if I just fudged it or if there is a "proper" way to go about it.

    I have a basic sensor setup. I am testing it right now by having 1 momentary push button. I got everything working all the way through to my openhab setup. However, when i push the button the state 1 is sent. Perfect. But as soon as I let go it sends 0. Now, I understand why it would. Makes total sense. But in this case, I only want something to happen when I press the button. Not when I release.

    Not sure if there is a better way to go about it, but I did this.

    if (value != oldValue) {
         // Send in the new value
         if (value==HIGH){
         gw.send(msg.set(value==HIGH ? 1 : 0));
         }
         oldValue = value;
      }
    

    I just wrapped the send with an If statement to only run the gw.send when it's high.

    Is there a better way to do this?


  • Mod

    @Jason-Brunk the code you have now could be reduced to

    if (value != oldValue) {
         if (value==HIGH){
             gw.send(msg.set(1));
         }
         oldValue = value;
      }
    

    So the sensor will only send high when the button is pressed, and will never send anything else. I don't think that's what you want.

    I think you want something like this:

    boolean state;
    boolean oldvalue;
    
    void loop(){
        value=digitalRead(PIN);
        if (value != oldvalue) {
            if (value == HIGH) {
                state = ! state; // switch state every time the button is down
                gw.send(msg.set(state));
            }
            oldvalue = value;
            gw.wait(100); // debounce
          }
    }
    

    I wrote this code on my ipad so it has not been checked for correct syntax but you should be able to get the idea.



  • I do want it to only send when it's high. Just didn't know if there was a way from the framework to do that or if just modding the code in some fashion like I did was the right way to go.


  • Mod

    Ok, then your code is fine. I would remove the HIGH ? part and just send 1, to make the code clearer, but it will work anyway.



  • Thank you. New to mysensors still so I didn't know if there was a "framework" method 🙂

    thanks again!


Log in to reply
 

Suggested Topics

  • 1
  • 2
  • 2
  • 3
  • 198
  • 2

0
Online

11.2k
Users

11.1k
Topics

112.5k
Posts