====== DI 割込を使用したプログラミング ======
v2.6.1 から、拡張 DI ポートに割込処理を追加しました。\\
**select() / poll() / epoll** を使用することで、DI の状態が変化するイベントを待つことができます。
\\
===== サンプルコード =====
==== C言語 ====
=== POLL ===
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
int fd, ret;
char c;
struct pollfd pfd;
/* DI: port 0 割込極性設定 */
fd = open("/sys/class/gpio/DI_00/edge", O_WRONLY);
write(fd, "both", 4); /* "rising" / "falling" / "both" */
close(fd);
/* DI: port 0 */
fd = open("/sys/class/gpio/DI_00/value", O_RDONLY);
pfd.fd = fd;
pfd.events = POLLPRI;
while (1) {
lseek(fd, 0, SEEK_SET);
/* 割込待ち: 5000 [ms] */
ret = poll(&pfd, 1, 5000);
read(fd, &c, 1);
if (ret != 0)
/* Event */
printf("DI: %c\n", c);
else
printf("timeouted...\n");
}
close(fd);
return 0;
}
\\
==== Python ====
=== EPOLL ===
#! /usr/bin/env python3
import select
def setup_gpios(nums):
gpios = {}
GPIO_BASE = "/sys/class/gpio/DI_%02d"
for i in range(nums):
# setup interrupt
open((GPIO_BASE + "/edge") % i, 'w').write("both")
f = open((GPIO_BASE + "/value") % i, "r")
# dummy read
f.readline()
gpios[f.fileno()] = (i, f)
return gpios
def main():
gpios = setup_gpios(8)
epoll = select.epoll()
for fd, info in gpios.items():
epoll.register(fd, select.EPOLLPRI)
for i in range(10):
print("waiting event...")
events = epoll.poll()
print(" event! nums = %d" % len(events))
for event in events:
fd = event[0]
info = gpios[fd]
print(" event in GPIO%d" % info[0])
info[1].seek(0)
val = int(info[1].readline().strip())
print(" value: %d" % val)
if __name__ == "__main__":
main()
\\
== 実行例 ==
root@plum:/tmp# python3 gpio_epoll.py
waiting event...
event! nums = 1
event in GPIO0
value: 1
waiting event...
event! nums = 1
event in GPIO0
value: 0
waiting event...
\\