-
Notifications
You must be signed in to change notification settings - Fork 0
/
hw2.c
120 lines (95 loc) · 2.42 KB
/
hw2.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
//Ron Ocampo
//Dinggao Pan
//HW2 EEM202A
//this program uses clock_gettime to timestamp pulses on pin4 of header P8
//
#include <time.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <poll.h>
#include <unistd.h>
//#include <fcntl.h>
struct timespec starttime;
struct timespec eventtime;
struct pollfd fds[1];
FILE *outfileptr;
FILE *exportfileptr;
FILE *unexportfileptr;
FILE *gpiodirectionptr;
FILE *gpioedgeptr;
FILE *gpiovalueptr;
FILE *gpioactive;
int rc = 0;
int firstpulse = 0;
double timedifference = 0;
//handle cntrl+c
void sigintHandler(int sig_num)
{
printf("\nTerminating \n");
fclose(outfileptr);
fclose(gpiovalueptr);
unexportfileptr = fopen("/sys/class/gpio/unexport", "w");
fprintf(unexportfileptr, "39");
fclose(unexportfileptr);
exit(0);
}
int main(int argc, char *argv[])
{
//check that path is given
if (argc!=2)
{
printf("invalid number of arguments\n");
printf("Usage: hw2 output/file/path.txt\n");
exit (-1);
}
//init handler
signal(SIGINT, sigintHandler);
//open file for writing
outfileptr = fopen(argv[1], "w");
//open pin
exportfileptr = fopen("/sys/class/gpio/export", "w");
fprintf(exportfileptr, "39"); //pin4 on header P8 gpio1[7]
fclose(exportfileptr);
//configure pin as input triggered on rising edge
gpiodirectionptr = fopen("/sys/class/gpio/gpio39/direction", "w");
fprintf(gpiodirectionptr, "in");
fclose(gpiodirectionptr);
gpioedgeptr = fopen("/sys/class/gpio/gpio39/edge", "w");
fprintf(gpioedgeptr, "rising");
fclose(gpioedgeptr);
void *buffer[64];
int clearreadbuff;
printf("Waiting for pulses...\n");
while(1)
{
gpiovalueptr = fopen("/sys/class/gpio/gpio39/value", "r");
fds[0].fd = fileno(gpiovalueptr);
fds[0].events = POLLPRI;
clearreadbuff = read(fds[0].fd, buffer, 64); //need this for some reason or poll wont work
rc = poll(fds, 1, -1);
if (rc == 0)
{
printf("Should not timeout\n");
}
if (rc == 1)
{
if (firstpulse == 0)
{
firstpulse =1;
fprintf(outfileptr, "%f\n", timedifference);
clock_gettime(CLOCK_MONOTONIC, &starttime);
}
else
{
clock_gettime(CLOCK_MONOTONIC, &eventtime);
long nsecdifference = eventtime.tv_nsec - starttime.tv_nsec;
double secdifferece = difftime(eventtime.tv_sec, starttime.tv_sec);
timedifference = secdifferece + (float)nsecdifference/1000000000.0;
fprintf(outfileptr, "%f\n", timedifference);
}
}
fclose(gpiovalueptr);
}
return 0;
}