概要 †
Raspberry Pi2のGPIOで、タクトスイッチ(トグル動作)を使ってみます。
Raspberry Pi/タクトスイッチのソースを変更しただけです。
配線 †
手順 †
- vi app.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
|
-
|
|
|
|
-
|
!
|
-
|
|
!
!
-
|
|
|
!
-
|
-
|
-
|
!
|
|
|
-
|
|
|
-
|
|
|
-
!
|
|
|
-
|
!
|
-
|
|
|
|
!
!
|
|
|
|
!
|
-
|
!
|
-
|
!
|
!
| #include <iostream>
#include <stdexcept>
#include <thread>
#include <chrono>
#include <wiringPi.h>
using namespace std;
namespace
{
constexpr int InPin = 24;
constexpr int OutPin = 25;
constexpr double DebounceMilliSec = 200.0;
enum class State : int
{
Low = 0,
High = 1
};
};
int main()
{
try
{
if (wiringPiSetupGpio() == -1)
{
throw runtime_error("Failed to wiringPiSetupGpio");
}
pinMode(InPin, INPUT);
pinMode(OutPin, OUTPUT);
wiringPiISR(InPin, INT_EDGE_RISING, [](){
static State lastState = State::Low;
static chrono::high_resolution_clock::time_point lastTime;
const auto currentTime = chrono::high_resolution_clock::now();
const auto duration = chrono::duration_cast<chrono::nanoseconds>(currentTime - lastTime).count();
const double durationMilliSec = duration / 1000000.0;
if (DebounceMilliSec > durationMilliSec)
{
cout << "skip\n";
}
else
{
cout << "run:" << durationMilliSec << "ms\n";
lastState = (lastState == State::Low)? State::High: State::Low;
digitalWrite(OutPin, static_cast<int>(lastState));
lastTime = currentTime;
}
});
int i = 0;
cin >> i;
cout << "exit...\n";
}
catch (exception& e)
{
cerr << e.what() << "\n";
}
catch (...)
{
cerr << "Unknown exception!\n";
}
return 0;
}
|
- vi Makefile
1
2
3
4
|
| app: app.cpp
g++ app.cpp -O2 -Wall -Wextra -std=gnu++11 -lwiringPi -oapp
clean:
rm -f *.o app
|
- ビルド/実行
検証時の環境 †