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
|
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/time.h>
#include <time.h>
#define MAX_BUF 64
struct timespec diff(struct timespec start, struct timespec end)
{
struct timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return temp;
}
int main( int argc, char** argv )
{
struct pollfd fdset[2];
int nfds = 2;
int gpio_fd, timeout, rc;
char buf[MAX_BUF];
int len;
int number=0;
struct timespec now_ts, then_ts, diff_ts;
bool firstInt; // the next interrupt is the first of the sequence
gpio_fd = open( "/sys/class/gpio/gpio15_pb2/value", O_RDONLY | O_NONBLOCK );
timeout = 500; //ms
clock_gettime(CLOCK_MONOTONIC, &then_ts);
firstInt=true;
while (1) {
memset((void*)fdset, 0, sizeof(fdset));
memset((void*)buf,0,sizeof(buf));
fdset[0].fd = 0;
fdset[0].events = POLLIN;
fdset[1].fd = gpio_fd;
fdset[1].events = POLLPRI;
rc = poll(fdset, nfds, timeout);
if (rc < 0) {
fprintf(stderr,"\npoll() failed!\n");
return -1;
}
// scaduto il timeout senza interrupt
if (rc == 0) {
// printf(".");
if (number > 0) {
printf("%d\n\n", number % 10);
number=0;
}
firstInt=true;
}
if (fdset[1].revents & POLLPRI) {
clock_gettime(CLOCK_MONOTONIC, &now_ts);
// printf("%d %d - ", now_ts.tv_sec, now_ts.tv_nsec);
diff_ts = diff(then_ts, now_ts);
then_ts = now_ts;
lseek(fdset[1].fd,0,SEEK_SET);
len = read(fdset[1].fd, buf, MAX_BUF);
// printf("\npoll() GPIO %d interrupt occurred\n", 34);
strtok(buf,"\n");
int sec=diff_ts.tv_sec;
float msec=diff_ts.tv_nsec/1000000.0;
// printf("value [%s] sec %d msec %f number pre %d\n",buf,sec,msec, number);
if (firstInt || msec > 90) number++;
firstInt=false;
}
if (fdset[0].revents & POLLIN) {
(void)read(fdset[0].fd, buf, 1);
fprintf(stderr, "\npoll() stdin read 0x%2.2X\n", (unsigned int) buf[0]);
}
fflush(stdout);
}
}
|