Application - Monitor GPIO interrupt in userspace

出自 flip the world
於 2018年8月23日 (四) 10:57 由 Tommy (對話 | 貢獻) 所做的修訂 (已建立頁面,內容為 "== Monitor GPIO 4 interrupt == === watch-button-glib.cpp === <pre> #include <glib.h> #include <fcntl.h> #include <iostream> using namespace std; #define buf_sz 10 st…")
(差異) ←上個修訂 | 最新修訂 (差異) | 下個修訂→ (差異)
前往: 導覽搜尋

Monitor GPIO 4 interrupt

watch-button-glib.cpp

#include <glib.h>
#include <fcntl.h>
#include <iostream>
using namespace std;
#define buf_sz 10
static int onButtonEvent(GIOChannel *channel, GIOCondition condition, gpointer user_data)
{
        static char buf[buf_sz];
        cerr << "onButtonEvent" <<endl;
        GError *error = 0;
        gsize bytes_read = 0;
        g_io_channel_seek_position(channel, 0, G_SEEK_SET, 0);
        GIOStatus rc = g_io_channel_read_chars(channel, buf, buf_sz - 1, &bytes_read, &error);
        cerr << "rc:" << rc << " data:" << buf <<endl;
        return 1;
}

int main(int argc, char** argv)
{
        GMainLoop* loop = g_main_loop_new(0,0);
        int fd = open("/sys/class/gpio/gpio4/value", O_RDONLY | O_NONBLOCK);
        GIOChannel* channel = g_io_channel_unix_new(fd);
        GIOCondition cond = GIOCondition( G_IO_PRI);
        guint id = g_io_add_watch(channel, cond, onButtonEvent, 0);

        g_main_loop_run(loop);
}

Makefile

watch-button-glib: watch-button-glib.cpp Makefile
        g++ watch-button-glib.cpp -o watch-button-glib -I/usr/include/glib-2.0 -I/usr/lib/arm-linux-gnueabihf/glib-2.0/include -lglib-2.0