-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpio.c
51 lines (48 loc) · 1.1 KB
/
gpio.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
#include <stdio.h>
#include <unistd.h>
int GPIO_setup(unsigned int pin, int value)
{
FILE *fp;
char path[128];
/* If the pin is already exported, unexport first */
if (access(path, F_OK)) {
snprintf(path, sizeof(path), "/sys/class/gpio/unexport");
if ((fp = fopen(path, "w")) == NULL) {
perror(path);
return 0;
}
fprintf(fp, "%d\n", pin);
fclose(fp);
}
/* Now export the pin */
snprintf(path, sizeof(path), "/sys/class/gpio/export");
if ((fp = fopen(path, "w")) == NULL) {
perror(path);
return 0;
}
fprintf(fp, "%d\n", pin);
fclose(fp);
usleep(50000); /* sys needs some time to adjust */
/* Now set direction (and initial value) */
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/direction", pin);
if ((fp = fopen(path, "w")) == NULL) {
perror(path);
return 0;
}
if (value == -1) {
fprintf(fp, "in\n");
fclose(fp);
} else {
fprintf(fp, "out\n");
fclose(fp);
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value",
pin);
if ((fp = fopen(path, "w")) == NULL) {
perror(path);
return 0;
}
fprintf(fp, "%d\n", value ? 1 : 0);
fclose(fp);
}
return 1;
}