SunFounder ESP32 Starter Kit
Code
Note:
• Open the 5.12_ultrasonic.ino file under the path of esp32-starter-kit-main\c\codes\5.
12_ultrasonic.
• After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.
• Always displaying “Unknown COMxx”?
After the code is successfully uploaded, the serial monitor will print out the distance between the ultrasonic sensor and
the obstacle ahead.
How it works?
About the application of ultrasonic sensor, we can directly check the subfunction.
float readSensorData(){// ...}
• The trigPin of the ultrasonic module transmits a 10us square wave signal every 2us.
// Trigger a low signal before sending a high signal
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10-microsecond high signal to the trigPin
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
// Return to low signal
digitalWrite(trigPin, LOW);
• The echoPin receives a high level signal if there is an obstacle within the range and use the pulseIn() function
to record the time from sending to receiving.
unsigned long microsecond = pulseIn(echoPin, HIGH);
• The speed of sound is 340 meters per second, which is equivalent to 29 microseconds per centimeter. By mea-
suring the time it takes for a square wave to travel to an obstacle and return, we can calculate the distance traveled
by dividing the total time by 2. This gives us the distance of the obstacle from the source of the sound wave.
98 Chapter 1. For Arduino User