-
Notifications
You must be signed in to change notification settings - Fork 0
/
beaglelib.cpp
105 lines (84 loc) · 1.83 KB
/
beaglelib.cpp
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
103
104
// beaglebone用 GPIOサポートユーティリティ
// リリース時、-DNDEBUG
#include "beaglelib.h"
bool is_port( int n ){ //Is gpio n already
string port = "/sys/class/gpio/gpio";
port += to_string( n );
ifstream ifs( port );
return ifs.good();
}
bool gpio_export( int n ){
if(!is_port( n )){
ofstream ofs("/sys/class/gpio/export");
ofs << to_string( n );
ofs.close();
return 1;
}
else{ return 0; }
}
void gpio_unexport( int n ){
ofstream ofs("/sys/class/gpio/unexport");
ofs << to_string( n );
}
void gpio_init_out( int n, int val){
string port = "/sys/class/gpio/gpio";
port += to_string( n );
if(!is_port( n )){ gpio_export(n); }
ofstream ofs;
ofs.open(port+"/direction");
ofs << "out";
ofs.close();
ofs.open(port+"/value");
ofs << to_string( val );
ofs.close();
}
void gpio_init_in( int n, int edge){
assert( edge >= 1 && edge <= 4 );
string port = "/sys/class/gpio/gpio";
port += to_string( n );
if(!is_port( n )){ gpio_export(n); }
ofstream ofs;
ofs.open(port+"/direction");
ofs << "in";
ofs.close();
string cedge;
switch(edge){
case 1:
cedge = "rising"; break;
case 2:
cedge = "falling"; break;
case 3:
cedge = "both"; break;
case 4:
cedge = "none"; break;
default:
cerr << "edge argment error" << endl;
}
ofs.open(port+"/edge");
ofs << cedge;
ofs.close();
}
void gpio_data_set( int n, int val){
if(!is_port( n )){
cerr << "port not exist" << endl;
return;
}
string port = "/sys/class/gpio/gpio";
port += to_string( n );
ofstream ofs;
ofs.open(port+"/value");
ofs << to_string( val );
ofs.close();
}
int gpio_data_get( int n ){
if(!is_port( n )){
cerr << "port not exist" << endl;
return false;
}
string port = "/sys/class/gpio/gpio";
port = port + to_string( n ) + "/value";
ifstream ifs(port);
string in;
ifs >> in;
return stoi(in);
}