Button code not working


Hi All, I’m trying to write some code to detect that a button was pushed. I wrote the code below, but it thinks the button is always pushed, except when I actually push it. When I push and hold it, the output stops. The button is wired between the GPIO pin and GND, with no pullup resistor since there is an internal pullup. I wonder if my code is wrong and would appreciate your comments, thank you.

I have pasted the relevant code below:

// GPIO 36
#define BTN_MOB 36

#ifdef BTN_MOB
mgos_gpio_set_mode(BTN_MOB, MGOS_GPIO_MODE_INPUT);

static void button_cb(int pin, void *pParam)
  if(pin == BTN_MOB)
    LOG(LL_INFO, ("***** BUTTON PRESSED\r\n"));

                  100 /* debounce ms */,
                  button_cb, /* callback handler */
                  NULL); /* arguments to callback handler */

As it turns out, GPIO pins 34, 35, 36 and 39 are actually GPI - input only and have no internal pullup or pulldown resistors. I switched to a different GPIO with internal pullup and this solved the problem.


Hi, Can you share full code? I’m interested in something similar to report a garage door open/close status based on a reed switch.

Thank you!


mgos_gpio_set_button_handler is what you need.


Thanks. I’ll look into it


I don’t think you need to switch to other pins. I’m successfully using pin 36 for my push button. But I do need to set “pull up” in code. Below a snippet of my code. It is in mJS/JavaScript, but the method signatures are similar.

GPIO.set_mode(36, GPIO.MODE_INPUT);
GPIO.set_pull(36, GPIO.PULL_DOWN);

GPIO.set_button_handler(INPUT_REPAIR_BUTTON, GPIO.PULL_UP, GPIO.INT_EDGE_NEG, 100, function(pin) {
    print("Button pressed:", pin);
}, true);

Perhaps this is out of date, but I don’t think so. If your circuit is working, it may just be luck. See page 2, Note 2: