-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgpio.c
More file actions
102 lines (97 loc) · 1.99 KB
/
gpio.c
File metadata and controls
102 lines (97 loc) · 1.99 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include "gpio.h"
int gpio_export(int pin)
{
int fd = open(GPIO_EXPORT_PATH, O_WRONLY);
if (fd == -1)
{
perror("[gpio_export] open");
return -1;
}
if (dprintf(fd, "%d", pin) == -1)
{
close(fd);
perror("[gpio_export] dprintf");
return -1;
}
close(fd);
return 0;
}
int gpio_unexport(int pin)
{
int fd = open(GPIO_UNEXPORT_PATH, O_WRONLY);
if (fd == -1)
{
perror("[gpio_unexport] open");
return -1;
}
if (dprintf(fd, "%d", pin) == -1)
{
close(fd);
perror("[gpio_unexport] dprintf");
return -1;
}
close(fd);
return 0;
}
int gpio_set_direction(int pin, gpio_direction direction)
{
char buffer[BUFLEN];
snprintf(buffer, BUFLEN, GPIO_DIRECTION_PATH, pin);
int fd = open(buffer, O_WRONLY);
if (fd == -1)
{
perror("[gpio_set_direction] open");
return -1;
}
if (dprintf(fd, (direction == IN) ? "in" : "out") == -1)
{
close(fd);
perror("[gpio_set_direction] dprintf");
return -1;
}
close(fd);
return 0;
}
int gpio_write(int pin, gpio_value value)
{
char buffer[BUFLEN];
snprintf(buffer, BUFLEN, GPIO_VALUE_PATH, pin);
int fd = open(buffer, O_WRONLY);
if (fd == -1)
{
perror("[gpio_write] open");
return -1;
}
if (dprintf(fd, "%d", value) == -1)
{
close(fd);
perror("[gpio_write] dprintf");
return -1;
}
close(fd);
return 0;
}
int gpio_read(int pin, gpio_value *value)
{
char buffer[BUFLEN];
snprintf(buffer, BUFLEN, GPIO_VALUE_PATH, pin);
int fd = open(buffer, O_RDONLY);
if (fd == -1)
{
perror("[gpio_read] open");
return -1;
}
if (read(fd, buffer, 3) < 1)
{
close(fd);
perror("[gpio_read] read");
return -1;
}
*value = atoi(buffer);
close(fd);
return 0;
}