-
Notifications
You must be signed in to change notification settings - Fork 0
/
interrupt.c
121 lines (94 loc) · 2.43 KB
/
interrupt.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
SYSFS gpio interrupt example for Raspberry Pi
*/
#define _GNU_SOURCE
#include <stddef.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <poll.h>
#include "interrupt.h"
static int write_file(const char *path, const char *str) {
int fd = 0;
if ((fd = open(path, O_WRONLY)) == 0) {
fprintf(stderr, "unable to open %s\n", path);
return 1;
}
if (write(fd, str, strlen(str)) < 1) {
fprintf(stderr, "unable to write to %s\n", path);
close(fd);
return 1;
}
close(fd);
return 0;
}
/* Register a sysfs GPIO pin to be interruptable
similar to:
$ echo 12 > /sys/class/gpio/export
$ echo both > /sys/class/gpio12/edge
$ echo in > /sys/class/gpio12/direction
*/
int int_register(int pin) {
char path[256];
char buffer[64];
/* begin by unregistering supplied pin, just in case */
(void) int_unregister(pin);
memset(buffer, 0, 64);
sprintf(buffer, "%d", pin);
if (write_file("/sys/class/gpio/export", buffer) != 0) {
return 1;
}
/* sleep 500 ms to let linux set up the dir .. */
usleep(500000);
memset(path, 0, 256);
sprintf(path, "%s%d/%s", "/sys/class/gpio/gpio", pin, "edge");
if (write_file(path, "both") != 0) {
return 1;
}
memset(path, 0, 256);
sprintf(path, "%s%d/%s", "/sys/class/gpio/gpio", pin, "direction");
if (write_file(path, "in") != 0) {
return 1;
}
return 0;
}
/* unregister an interrupt gpio config
similar to:
$ echo 12 > /sys/class/gpio/unexport
*/
int int_unregister(int pin) {
char buffer[64];
memset(buffer, 0, 64);
sprintf(buffer, "%d", pin);
if (write_file("/sys/class/gpio/unexport", buffer) != 0) {
return 1;
}
usleep(50000); /* sleep 50 ms */
return 0;
}
/* poll a gpio pin for interrupt event
blocking
*/
int int_poll(int pin) {
int fd;
struct pollfd pfd;
char path[256];
char buf[16];
memset(path, 0, 256);
sprintf(path, "%s%d/%s", "/sys/class/gpio/gpio", pin, "value");
if ((fd = open(path, O_RDONLY)) == 0) {
fprintf(stderr, "unable to open %s\n", path);
return 1;
}
pfd.fd = fd;
pfd.events = POLLPRI | POLLERR;
lseek(fd, 0, SEEK_SET);
read(fd, buf, sizeof buf);
poll(&pfd, 1, -1);
lseek(fd, 0, SEEK_SET);
read(fd, buf, sizeof buf);
return 0;
}