EasyManua.ls Logo

Freenove ESP32 - Page 113

Default Icon
159 pages
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
Need support? support@freenove.com
111
Chapter 10 Ultrasonic Ranging
www.freenove.com
The function that gets ultrasonic data.
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
float getSonar() {
unsigned long pingTime, t0, t1;
float distance;
// make PIN_TRIG output high level lasting for 10μs to triger HC_SR04
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
// Wait HC-SR04 returning to the high level and measure out this waitting time
t0 = micros();
pingTime = pulseIn(PIN_ECHO, HIGH, timeOut); // unit: us
t1 = micros() - t0;
// calculate the distance according to the time
if (t1 < timeOut) {
distance = (float)pingTime * soundVelocity / 2 / 10000;
} else {
distance = MAX_DISTANCE;
}
return distance; // return the distance value
}
About function pulseIn():
int pulseIn(int pin, int level, int timeout);
pin: the number of the Arduino pin on which you want to read the pulse. Allowed data types: int.
value: type of pulse to read: either HIGH or LOW. Allowed data types: int.
timeout (optional): the number of microseconds to wait for the pulse to start; default is one second.

Related product manuals