-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHC_SR04.cpp
81 lines (77 loc) · 2.4 KB
/
HC_SR04.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
#include "HC_SR04.h"
HC_SR04::HC_SR04(PinName trigPin, PinName echoPin, Kernel::Clock::duration_u32 updateRate, Kernel::Clock::duration_u32 timeout):_trig(trigPin), _echo(echoPin)
{
_updateRate = updateRate;
_timeout = timeout;
}
HC_SR04::HC_SR04(PinName trigPin, PinName echoPin, Kernel::Clock::duration_u32 updateRate, Kernel::Clock::duration_u32 timeout, void onUpdate(int))
:_trig(trigPin), _echo(echoPin)
{
_onUpdateMethod = onUpdate;
_updateRate = updateRate;
_timeout = timeout;
_t.start ();
}
void HC_SR04::_startT()
{
if(chrono::duration_cast<chrono::milliseconds>(_t.elapsed_time()).count()>600)
{
_t.reset ();
}
start = chrono::duration_cast<chrono::microseconds>(_t.elapsed_time()).count();
}
void HC_SR04::_updateDist()
{
end = chrono::duration_cast<chrono::microseconds>(_t.elapsed_time()).count();
done_flag = true;
_distance = (end - start)/6;
_tout.detach();
_tout.attach(callback(this,&HC_SR04::_startTrig), _updateRate);
}
void HC_SR04::_startTrig(void)
{
_tout.detach();
_trig=1;
wait_us(10);
done_flag = false;
_echo.rise(callback(this,&HC_SR04::_startT));
_echo.fall(callback(this,&HC_SR04::_updateDist));
_echo.enable_irq ();
_tout.attach(callback(this,&HC_SR04::_startTrig),_timeout);
_trig=0;
}
int HC_SR04::getCurrentDistance(void)
{
return _distance;
}
void HC_SR04::pauseUpdates(void)
{
_tout.detach();
_echo.rise(NULL);
_echo.fall(NULL);
}
void HC_SR04::startUpdates(void)
{
_startTrig();
}
void HC_SR04::attachOnUpdate(void method(int))
{
_onUpdateMethod = method;
}
void HC_SR04::setUpdateRate(Kernel::Clock::duration_u32 updateRate)
{
_updateRate = updateRate;
}
bool HC_SR04::isUpdated(void)
{
bool temp_flag = done_flag;
done_flag = false;
return temp_flag;
}
void HC_SR04::checkDistance(void)
{
if(isUpdated())
{
(*_onUpdateMethod)(_distance);
}
}