-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHCSR04.cpp
89 lines (81 loc) · 2.2 KB
/
HCSR04.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
/*
HCSR04.h - Library for interacting with HCSR04 sensor.
Created by Dirk Köhler.
*/
#include "Arduino.h"
#include "HCSR04.h"
HCSR04::HCSR04(byte triggerPin, byte sensorPin)
{
_triggerPin = triggerPin;
_sensorPin = sensorPin;
pinMode(_triggerPin, OUTPUT);
pinMode(_sensorPin, INPUT);
_echoTimeout = _sensorMaxDistance / sonicSpeed;
}
//reading echo time from sensor
unsigned long HCSR04::readEchoTime()
{
//disable trigger for x miliseconds to get a clear signal
digitalWrite(_triggerPin, LOW);
delayMicroseconds(3);
//sending and receiving new signal, using interrupts in fact of time critival function
noInterrupts();
digitalWrite(_triggerPin, HIGH);
delayMicroseconds(_measurementInterval);
digitalWrite(_triggerPin, LOW);
_echoTime = pulseIn(_sensorPin, HIGH, _echoTimeout);
interrupts();
//check if returns timeout
if (_echoTime > 0)
{
_echoTime = (_echoTime / 2);
}
else
{
_echoTime = 0;
}
return _echoTime;
}
//reading x signals and returning average value
unsigned int HCSR04::getAverage(int countAverageMeasurements)
{
unsigned long measurementValues[countAverageMeasurements];
for (int i = 0; i <= countAverageMeasurements; i++)
{
measurementValues[i] = readEchoTime();
//delay to prevent overlapping sensor readings
delayMicroseconds(_echoTimeout * 2);
}
unsigned long sumMeasurementvalues = 0;
for (int i = 0; i <= countAverageMeasurements; i++)
{
sumMeasurementvalues += measurementValues[i];
}
return sumMeasurementvalues / countAverageMeasurements;
}
//get single distance measurement value
unsigned int HCSR04::getDistance(boolean average = true, int countAverageMeasurements = 10)
{
if (average == true)
{
return getAverage(countAverageMeasurements) * sonicSpeed;
}
else
{
return readEchoTime() * sonicSpeed;
}
}
//check if there is an obstacle in giving range
boolean HCSR04::getObstacle(int range, boolean average = true, int countAverageMeasurements = 10)
{
int distance = getDistance(average, countAverageMeasurements);
//check if in distance and if measurement is not zero by timeout
if (distance <= range && distance > 0)
{
return true;
}
else
{
return false;
}
}