-
Notifications
You must be signed in to change notification settings - Fork 0
/
GPIOClass.cpp
90 lines (74 loc) · 2.72 KB
/
GPIOClass.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
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include "GPIOClass.h"
using namespace std;
GPIOClass::GPIOClass(){
this->gpionum = "4"; //GPIO4 is default
}
GPIOClass::GPIOClass(string gnum){
this->gpionum = gnum; //Instatiate GPIOClass object for GPIO pin number "gnum"
}
int GPIOClass::export_gpio(){
string export_str = "/sys/class/gpio/export";
ofstream exportgpio(export_str.c_str()); // Open "export" file. Convert C++ string to C string. Required for all Linux pathnames
if (exportgpio < 0){
cout << " OPERATION FAILED: Unable to export GPIO"<< this->gpionum <<" ."<< endl;
return -1;
}
exportgpio << this->gpionum ; //write GPIO number to export
exportgpio.close(); //close export file
return 0;
}
int GPIOClass::unexport_gpio(){
string unexport_str = "/sys/class/gpio/unexport";
ofstream unexportgpio(unexport_str.c_str()); //Open unexport file
if (unexportgpio < 0){
cout << " OPERATION FAILED: Unable to unexport GPIO"<< this->gpionum <<" ."<< endl;
return -1;
}
unexportgpio << this->gpionum ; //write GPIO number to unexport
unexportgpio.close(); //close unexport file
return 0;
}
int GPIOClass::setdir_gpio(string dir){
string setdir_str ="/sys/class/gpio/gpio" + this->gpionum + "/direction";
ofstream setdirgpio(setdir_str.c_str()); // open direction file for gpio
if (setdirgpio < 0){
cout << " OPERATION FAILED: Unable to set direction of GPIO"<< this->gpionum <<" ."<< endl;
return -1;
}
setdirgpio << dir; //write direction to direction file
setdirgpio.close(); // close direction file
return 0;
}
int GPIOClass::setval_gpio(string val){
string setval_str = "/sys/class/gpio/gpio" + this->gpionum + "/value";
ofstream setvalgpio(setval_str.c_str()); // open value file for gpio
if (setvalgpio < 0){
cout << " OPERATION FAILED: Unable to set the value of GPIO"<< this->gpionum <<" ."<< endl;
return -1;
}
setvalgpio << val ;//write value to value file
setvalgpio.close();// close value file
return 0;
}
int GPIOClass::getval_gpio(string& val){
string getval_str = "/sys/class/gpio/gpio" + this->gpionum + "/value";
ifstream getvalgpio(getval_str.c_str());// open value file for gpio
if (getvalgpio < 0){
cout << " OPERATION FAILED: Unable to get value of GPIO"<< this->gpionum <<" ."<< endl;
return -1;
}
getvalgpio >> val ; //read gpio value
if(val != "0")
val = "1";
else
val = "0";
getvalgpio.close(); //close the value file
return 0;
}
string GPIOClass::get_gpionum(){
return this->gpionum;
}