forked from omaraflak/HC-SR04-Raspberry-Pi-C-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibSonar.cpp
56 lines (43 loc) · 1.05 KB
/
libSonar.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
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pigpio.h>
#include "libSonar.h"
Sonar::Sonar(){}
void Sonar::init(const uint8_t &trigger, const uint8_t &echo)
{
this->trigger=trigger;
this->echo=echo;
gpioSetMode(trigger, PI_OUTPUT);
gpioSetMode(echo, PI_INPUT);
}
double Sonar::distance()
{
gpioWrite(trigger, PI_HIGH);
gpioDelay(10);
gpioWrite(trigger, PI_LOW);
double startTime = time_time();
double arrivalTime = time_time();
while(gpioRead(echo) == PI_LOW) {
startTime = time_time();
}
while(gpioRead(echo) == PI_HIGH) {
arrivalTime = time_time();
}
double timeElapsed = arrivalTime - startTime;
double distanceCalculated = (timeElapsed * 34300) / 2;
return distanceCalculated;
}
double Sonar::speed()
{
double distance1 = distance();
usleep(1000000);
double distance2 = distance();
double speedMeasured = (distance2 - distance1) / 1.0;
return speedMeasured;
}
Sonar::~Sonar()
{
gpioTerminate();
}