0

Using the pigpio library, I wanted to detect when a button is pressed and turn on/off an LED. I am trying to use the gpioSetAlertFunc function to trigger the LED when the button is detected as pressed. But when I press the button, the LED does not light up. Am I using gpioSetAlertFunc function wrongly? I used the circuit (pins different) similar to this: https://www.sunfounder.com/learn/Super_Kit_V2_for_RaspberryPi/lesson-2-controlling-an-led-by-a-button-super-kit-for-raspberrypi.html

#include <pigpio.h>
#include <stdio.h>

static int LED_gpio = 14;
static int Button_gpio = 21;

void triggerLED(int gpio, int level, uint32_t tick)
{
    if (gpioRead(LED_gpio) == 0)
        gpioWrite(LED_gpio, 1);
    else
    gpioWrite(LED_gpio, 0);
}


int main(void)
{
    int status = gpioInitialise();

    if (status > 0)
    {
        gpioSetMode(LED_gpio, PI_OUTPUT);
        gpioSetMode(Button_gpio, PI_INPUT);

        gpioSetAlertFunc(Button_gpio, triggerLED);

        while (1)
        {
        } 
    }
    gpioTerminate();

}

closed as unclear what you're asking by techraf, Jacobm001 Jan 23 '18 at 0:08

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

0

It will work but will not be as efficient as it might.

The empty while loop will consume 100% of a CPU core. It is better to let other things run so I would use the following style.

while (1)
{
   sleep(1); /* sleep for one second */
}

Also note that pigpio tells you if you were alerted because the GPIO went high (became level 1) or went low (became level 0). You should not read the level in the alert function. It may have changed again between the interrupt and the C program running. If it has changed again you will shortly get a new alert with the new level.

So I suggest.

void triggerLED(int gpio, int level, uint32_t tick)
{
    if (level == 0)
        gpioWrite(LED_gpio, 1);
    else
    gpioWrite(LED_gpio, 0);
}

or perhaps

void triggerLED(int gpio, int level, uint32_t tick)
{
    if (level)
        gpioWrite(LED_gpio, 0);
    else
        gpioWrite(LED_gpio, 1);
}

Finally remember that pigpio only ever uses (Broadcom) GPIO numbers. So 14 refers to GPIO 14 (pin 8) and 21 refers to GPIO 21 (pin 40).

Not the answer you're looking for? Browse other questions tagged or ask your own question.