-
Notifications
You must be signed in to change notification settings - Fork 0
/
chip.h
73 lines (65 loc) · 1.56 KB
/
chip.h
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
#ifndef __CHIP_H__
#define __CHIP_H__
#include <stdio.h>
#include <stdlib.h>
#define PIN0 "1013"
//Opens new GPIO pin
//Does not check if GPIO pin exists
int open_pin(char* pin) {
FILE * f = fopen("/sys/class/gpio/export", "w");
if (f == NULL) return -1;
fputs(pin, f); //exports pin
fclose(f);
return 0;
}
//Closes GPIO pin
int close_pin(char* pin) {
FILE * f = fopen("/sys/class/gpio/unexport", "w");
if (f == NULL) return -1;
fputs(pin, f); //exports pin
fclose(f);
return 0;
}
//Writes direction of pin (IN/OUT)
int write_dir(char* pin, char* d) {
char tmp[50];
sprintf(tmp, "/sys/class/gpio/gpio%s/direction", pin);
FILE * f = fopen(tmp, "w");
if (f == NULL) return -1;
fputs(d, f); //set direction of pin
fclose(f);
return 0;
}
//Writes value of pin -- (pin = out, 1/0)
int write_val(char* pin, char* v) {
char tmp[50];
sprintf(tmp, "/sys/class/gpio/gpio%s/value", pin);
FILE * f = fopen(tmp, "w");
if (f == NULL) return -1;
fputs(v, f); //set value of pin
fclose(f);
return 0;
}
//Read value from pin -- (1/0)
int read_value(char* pin, char* ret_val) {
char tmp[50];
sprintf(tmp, "/sys/class/gpio/gpio%s/value", pin);
FILE * f = fopen(tmp, "r");
if (f == NULL){
ret_val = "error";
return -1;
}
fscanf(f, "%s", ret_val); //read value of pin
fclose(f);
return 0;
}
//Check if program is run on CHIP w/ sudo access
int has_gpio_access() {
if (open_pin(PIN0) == 0) {
close_pin(PIN0);
return 1;
} else {
return 0;
}
}
#endif