-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpin_io.c
More file actions
95 lines (79 loc) · 1.91 KB
/
pin_io.c
File metadata and controls
95 lines (79 loc) · 1.91 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
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int fd;
void export_pin(int, int);
void setup_pin(int);
void set_pin(int, int);
void export_pin(int pin, int export_state)
{
char pin_str[2];
sprintf(pin_str, "%d", pin);
if (export_state)
{
printf("Exporting pin: %d\n", pin);
int fd = open("/sys/class/gpio/export", O_WRONLY);
if (write(fd, pin_str, 2) != 2)
{
perror("Error writing to /sys/class/gpio/export");
}
}
else
{
printf("Unexporting pin: %d\n", pin);
fd = open("/sys/class/gpio/unexport", O_WRONLY);
if (write(fd, pin_str, 2) != 2)
{
perror("Error writing to /sys/class/gpio/unexport");
}
}
close(fd);
}
void setup_pin(int pin)
{
char path[50];
sprintf(path, "/sys/class/gpio/gpio%d/direction", pin);
FILE *direction_file = fopen(path, "w");
if (direction_file == NULL)
{
perror("Unable to open GPIO direction file");
exit(1);
}
if (fprintf(direction_file, "out") < 0)
{
perror("Error writing to GPIO direction file");
exit(1);
}
fclose(direction_file);
}
void set_pin(int pin, int state)
{
char path[50];
sprintf(path, "/sys/class/gpio/gpio%d/value", pin);
char state_str[2];
if (!state)
{
strcpy(state_str, "0");
}
else
{
strcpy(state_str, "1");
}
FILE *value_file = fopen(path, "w");
if (value_file == NULL)
{
perror("Unable to open GPIO direction file");
exit(1);
}
if (fprintf(value_file, state_str) < 0)
{
perror("Error writing to GPIO direction file");
exit(1);
}
fclose(value_file);
}