-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbutton.cpp
91 lines (77 loc) · 1.53 KB
/
button.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
#include "button.h"
#include "buttonpoll.h"
#include <cstdio> // std::perror()
#include <fcntl.h> // open()
#include <poll.h> // poll()
#include <fstream> // std::fstream
Button::Button(int pin, int edge)
{
_gpio_pin = pin;
pinExport();
setDirection();
setEdge(edge);
std::string path = SYSFS_GPIO_DIR + "/gpio" + std::to_string(_gpio_pin) + "/value";
_fd = open(path.c_str(), O_RDONLY | O_NONBLOCK);
if(_fd < 0)
std::perror(path.c_str());
}
bool Button::pinExport()
{
std::string path = SYSFS_GPIO_DIR + "/export";
std::fstream file;
file.open(path);
if(!file.is_open())
{
std::perror(path.c_str());
return false;
}
auto data = std::to_string(_gpio_pin);
file << data;
file.close();
return true;
}
bool Button::setDirection()
{
std::string path = SYSFS_GPIO_DIR + "/gpio" + std::to_string(_gpio_pin) + "/direction";
std::fstream file;
file.open(path);
if(!file.is_open())
{
std::perror(path.c_str());
return false;
}
std::string data = "in";
file << data;
file.close();
return true;
}
bool Button::setEdge(int edge)
{
std::string path = SYSFS_GPIO_DIR + "/gpio" + std::to_string(_gpio_pin) + "/edge";
std::fstream file;
file.open(path);
if(!file.is_open())
{
std::perror(path.c_str());
return false;
}
std::string data;
switch(edge)
{
case ButtonPoll::Rising:
data = "rising";
break;
case ButtonPoll::Falling:
data = "falling";
break;
case ButtonPoll::Both:
data = "both";
break;
default:
file.close();
return false;
}
file << data;
file.close();
return true;
}