How to add a button handler to GPIO pin through a push button

37 views Asked by At

I have created a user space application as a systemd service in Yocto to generate a syslog "button pressed" when button is pressed, where the button is connected to GPIO pin 193.My code is as follows

#include <stdio.h>
#include <unistd.h>
#include <syslog.h>
#include <fcntl.h>
#include <systemd/sd-event.h>

#define GPIO_PIN "/sys/class/gpio/gpio1009/value" // 1009 is pin 193 since chip number is 816

int button_event_callback(sd_event_source *source, int fd, uint32_t revents, void *userdata)
{
    char value;
    ssize_t bytes_read = read(fd, &value, 1); // Read the value of the GPIO pin

    if (bytes_read == -1) {
        perror("Error reading GPIO pin value");
        return -1;
    }

    if (value == '0') {
        syslog(LOG_INFO,"Button pressed!\n");
        printf("Button Pressed!\n");
    }

    return 0;
}

int main()
{
    sd_event *event_loop = NULL;

    sd_event_new(&event_loop);

    int button_fd = open(GPIO_PIN, O_RDONLY); // Open the GPIO pin value file

    if (button_fd == -1) {
        perror("Error opening GPIO pin file");
        return 1;
    }

    sd_event_add_io(event_loop, NULL, button_fd, EPOLLIN, button_event_callback, NULL);

    syslog(LOG_INFO,"Listening for button press events.\n");

    sd_event_run(event_loop,-1);
    sd_event_unref(event_loop);

    return 0;
}

My service file is

[Unit]
Description=Continuous Hello World Service
after=syslog.target

[Service]
ExecStart=/usr/bin/buttonser
standardOutput=syslog
Type=simple
Restart=always

[Install]
WantedBy=multi-user.target

I need to run this a service whenever the button connected to GPIO pin 193 is pressed need to get a log in syslog.

Give me suggestions how I can achieve these.

0

There are 0 answers