-
Notifications
You must be signed in to change notification settings - Fork 0
/
measure.cpp
41 lines (32 loc) · 824 Bytes
/
measure.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
#include <iostream>
#include <wiringPi.h>
#include "libHCSR04.h"
HCSR04::HCSR04(){}
void HCSR04::init(int trigger, int echo)
{
this->trigger=trigger;
this->echo=echo;
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT);
digitalWrite(trigger, LOW);
delay(500);
}
double HCSR04::distance(int timeout)
{
delay(10);
digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);
now=micros();
while (digitalRead(echo) == LOW && micros()-now<timeout);
recordPulseLength();
travelTimeUsec = endTimeUsec - startTimeUsec;
distanceMeters = 100*((travelTimeUsec/1000000.0)*340.29)/2;
return distanceMeters;
}
void HCSR04::recordPulseLength()
{
startTimeUsec = micros();
while ( digitalRead(echo) == HIGH );
endTimeUsec = micros();
}