-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathultrasonic.h
48 lines (37 loc) · 1.22 KB
/
ultrasonic.h
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
#ifndef ULTRASONIC_H
#define ULTRASONIC_H
#include "esphome.h"
//define sound speed in mm/uS
#define SOUND_SPEED 0.34
class Ultrasonic {
private:
int trigPin;
int echoPin;
public:
Ultrasonic() {};
Ultrasonic(int trigPin, int echoPin) {
this->trigPin = trigPin;
this->echoPin = echoPin;
if(trigPin == 1)
pinMode(1, FUNCTION_3);
if(echoPin == 3)
pinMode(3, FUNCTION_3);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
float getDistanceMm() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
double duration = pulseIn(echoPin, HIGH);
// Calculate the distance
return duration * SOUND_SPEED/2;
}
~Ultrasonic(){}
};
#endif //ULTRASONIC_H