-
Notifications
You must be signed in to change notification settings - Fork 5
/
gpio.c
93 lines (71 loc) · 1.38 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
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
#include "gpio.h"
int gpio_pin_exists(int port)
{
int pin[] = {135,136,137,138,139,143,144,145,146};
int i;
for(i=0; i < 9; i++)
if(port == pin[i])
return 0;
return -1;
}
int gpio_open(int port, int DDR)
{
FILE *f;
char file[35],ris[5];
if(gpio_pin_exists(port) == -1)
return -1;
f = fopen(EXPORT, "w");
if (fprintf(f, "%d\n", port) < 0)
return -2;
fclose(f);
sprintf(file, "/sys/class/gpio/gpio%d/direction", port);
f = fopen(file, "w");
if (!DDR)
sprintf(ris,IN);
else
sprintf(ris,OUT);
if (fprintf(f, "%s",ris) < 0)
return -2;
fclose(f);
return 0;
}
int gpio_close(int port)
{
FILE *f;
if(gpio_pin_exists(port) == -1)
return -1;
f = fopen(UNEXPORT, "w");
if(fprintf(f, "%d\n", port) < 0)
return -2;
fclose(f);
return 0;
}
int gpio_read(int port)
{
FILE *f;
char file[31];
int i;
if(gpio_pin_exists(port) == -1)
return -1;
sprintf(file, "/sys/class/gpio/gpio%d/value", port);
f = fopen(file, "r");
fscanf(f, "%d", &i);
fclose(f);
return i;
}
int gpio_write(int port, int value){
FILE *f;
char file[35],ris[5];
if (gpio_pin_exists(port) == -1)
return -1;
sprintf(file, "/sys/class/gpio/gpio%d/value", port);
f = fopen(file, "w");
if (!value)
sprintf(ris,LOW);
else
sprintf(ris,HIGH);
if (fprintf(f, "%s",ris) < 0)
return -2;
fclose(f);
return 0;
}