HC-SR04 distance
Measure distance with an ultrasonic sensor. The echo pin is 5 V, so it goes through a divider.
ESP32
3V3
GND
EN
23
VP
22
VN
TX
34
RX
35
21
32
GND
33
19
25
18
26
5
27
17
14
16
12
4
GND
0
13
2
D2
15
D3
D1
CMD
D0
5V
CLK
Wiring
| From | To board | Note |
|---|---|---|
| HC-SR04 VCC | 5V | |
| HC-SR04 GND | GND | |
| HC-SR04 TRIG | GPIO 5 | |
| HC-SR04 ECHO, through 1 kΩ | GPIO 18 | Add 2 kΩ from GPIO 18 to GND to drop 5 V to 3.3 V |
Tested on this board
Not run on this board yet. Treat the wiring and code as a first draft.
Firmware, Arduino sketch for ESP32 Dev Module
const int TRIG = 5;
const int ECHO = 18;
void setup() {
Serial.begin(115200);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
unsigned long us = pulseIn(ECHO, HIGH, 30000);
if (us == 0) {
Serial.println("No echo");
} else {
Serial.printf("%.1f cm\n", us * 0.0343 / 2);
}
delay(500);
}Parts
| Quantity | Part | Where to buy |
|---|---|---|
| 1× | ESP32 dev board | Buy at Amazon |
| 1× | HC-SR04 ultrasonic sensor | |
| 1× | 1 kΩ resistor | |
| 1× | 2 kΩ resistor | |
| 4× | Jumper wires |
Amazon buy links may include an Associates tag, and this site may earn a commission from qualifying Amazon purchases at no extra cost to you. Adafruit links are direct.
Libraries
None beyond the ESP32 Arduino core.
Load it
- In the Arduino IDE, install the esp32 board package and pick the board named above the sketch.
- Paste the sketch, choose the board's port and upload. Hold BOOT if the upload stalls at Connecting.
- Close the IDE's serial monitor, then open the bench here to watch the output.