-
Notifications
You must be signed in to change notification settings - Fork 0
/
ultrasonicSensor.cpp
47 lines (39 loc) · 1.69 KB
/
ultrasonicSensor.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
/******************************************************************************
* *
* Program : FileLogger *
* *
* FILE : ultrasonicSensor.cpp *
* *
* Date : 28 / 05 / 2021 *
* *
* Programmers : Team Software "TORQ" *
* *
******************************************************************************/
#include "ultrasonicSensor.h"
UltrasonicSensor::UltrasonicSensor(byte m_echo_pin, byte m_trig_pin)
{
echo_pin = m_echo_pin;
trig_pin = m_trig_pin;
duration = 0.0;
distance = 0;
}
void UltrasonicSensor::init()
{
pinMode(trig_pin, OUTPUT);
pinMode(echo_pin, INPUT);
}
int UltrasonicSensor::get_distance()
{
// Clears the trig_pin condition
digitalWrite(trig_pin, LOW);
delayMicroseconds(2);
// Sets the trig_pin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trig_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trig_pin, LOW);
// Reads the echo_pin, returns the sound wave travel time in microseconds
duration = pulseIn(echo_pin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
return distance;
}