已建立頁面,內容為 "== 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…" |
Consistency: syntax highlighting for code, File: prefix |
||
| (未顯示同一使用者於中間所作的 2次修訂) | |||
| 第1行: | 第1行: | ||
Watching a '''GPIO interrupt from userspace''' on a Raspberry Pi with a small GLib program, rather than polling the pin. | |||
== Monitor GPIO 4 interrupt == | == Monitor GPIO 4 interrupt == | ||
=== watch-button-glib.cpp === | === watch-button-glib.cpp === | ||
< | <syntaxhighlight lang="c"> | ||
#include <glib.h> | #include <glib.h> | ||
#include <fcntl.h> | #include <fcntl.h> | ||
| 第30行: | 第32行: | ||
} | } | ||
</ | </syntaxhighlight> | ||
=== Makefile === | === Makefile === | ||
| 第37行: | 第39行: | ||
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 | 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 | ||
</pre> | </pre> | ||
[[Category:Projects]] | |||
2026年8月23日 (日) 18:01的最新修訂
Watching a GPIO interrupt from userspace on a Raspberry Pi with a small GLib program, rather than polling the pin.
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