-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpio.cpp
87 lines (64 loc) · 1.89 KB
/
gpio.cpp
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
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
// Export the desired pin by writing to /sys/class/gpio/export
int fd = open("/sys/class/gpio/export", O_WRONLY);
if (fd == -1) {
perror("Unable to open /sys/class/gpio/export");
exit(1);
}
if (write(fd, "418", 3) != 3) {
perror("Error writing to /sys/class/gpio/export");
exit(1);
}
close(fd);
// Set the pin to be an output by writing "out" to /sys/class/gpio/gpio24/direction
fd = open("/sys/class/gpio/gpio418/direction", O_WRONLY);
if (fd == -1) {
perror("Unable to open /sys/class/gpio/gpio24/direction");
exit(1);
}
if (write(fd, "out", 3) != 3) {
perror("Error writing to /sys/class/gpio/gpio418/direction");
exit(1);
}
close(fd);
fd = open("/sys/class/gpio/gpio418/value", O_WRONLY);
if (fd == -1) {
perror("Unable to open /sys/class/gpio/gpio418/value");
exit(1);
}
// Toggle LED 500 ms on, 500ms off, 10 times (10 seconds)
for (int i = 0; i < 10; i++) {
if (write(fd, "1", 1) != 1) {
perror("Error writing to /sys/class/gpio/gpio418/value");
exit(1);
}
usleep(500000);
if (write(fd, "0", 1) != 1) {
perror("Error writing to /sys/class/gpio/gpio418/value");
exit(1);
}
usleep(500000);
}
close(fd);
// Unexport the pin by writing to /sys/class/gpio/unexport
fd = open("/sys/class/gpio/unexport", O_WRONLY);
if (fd == -1) {
perror("Unable to open /sys/class/gpio/unexport");
exit(1);
}
if (write(fd, "418", 3) != 3) {
perror("Error writing to /sys/class/gpio/unexport");
exit(1);
}
close(fd);
// And exit
return 0;
}