ESP32 S3 - Ultrasonic Sensor - Servo Motor

This tutorial shows you how to use the ESP32 S3 with an HC-SR04 ultrasonic sensor to automatically control a servo motor based on the distance of a detected object. By combining non-contact distance measurement with precise angular actuation, you can build responsive proximity-triggered systems without any physical interaction.

What you'll build:

  1. An ESP32 S3 circuit with an HC-SR04 ultrasonic sensor and a servo motor wired to the board
  2. A sketch that reads the distance from the ultrasonic sensor continuously
  3. A servo motor that rotates to 90° when an object is detected close to the sensor
  4. A servo motor that returns to 0° automatically when the object moves away

https://newbiely.com/images/cover/esp32-s3-ultrasonic-sensor-servo-motor.jpg

Hardware Preparation

1×ESP32 S3 WROOM N16R8
1×Alternatively, ESP32 S3 SuperMini Dev Module
1×Alternatively, ESP32 S3 Uno-form Board
1×Alternatively, ESP32 S3 Camera Board
1×USB Cable Type-A to Type-C (for USB-A PC)
1×USB Cable Type-C to Type-C (for USB-C PC)
1×Ultrasonic Sensor
1×Servo Motor
1×Breadboard
1×Jumper Wires
1×Optionally, DC Power Jack
1×Recommended: Screw Terminal Expansion Board for ESP32 S3
1×Recommended: Breakout Expansion Board for ESP32 S3
1×Recommended: Power Splitter for ESP32 S3

Or you can buy the following kits:

1×DIYables ESP32 S3 Starter Kit (ESP32 S3 included)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables .

Buy Note: For controlling multiple servo motors, use the PCA9685 16 Channel PWM Servo Driver Module to save MCU pins and simplify wiring.

Overview of Servo Motor and Ultrasonic Sensor

The HC-SR04 ultrasonic sensor and servo motor are a powerful combination for the ESP32 S3: the sensor provides non-contact distance data while the servo delivers precise, repeatable angular output in response to that data. Together they enable a wide class of proximity-aware automation projects — from automatic doors and robotic arm triggers to parking barriers and object-avoidance mechanisms.

Key Specifications

We have specific tutorials about each component covering detailed hardware pinout, working principles, wiring to the ESP32 S3, and full code examples. Learn more at the links below:

Wiring Diagram

Connect the HC-SR04 and the servo motor to your ESP32 S3 as shown in the diagram below. Make sure both the ultrasonic sensor's VCC and the servo motor's power wire are connected to the 5V rail, since neither component operates correctly at 3.3V.

Safety Notes

Servo motors can briefly draw several hundred milliamps under load, which can stress the ESP32 S3's USB supply if used for extended periods. For bench testing, the USB port is generally sufficient; for any deployment scenario, power the servo from a dedicated 5V external supply and share only the GND rail with the ESP32 S3. Similarly, always connect the HC-SR04 VCC pin to 5V — not 3.3V — to ensure accurate ultrasonic measurements.

The wiring diagram between ESP32 S3 Ultrasonic Sensor Servo Motor

This image is created using Fritzing. Click to enlarge image

Component Pin ESP32 S3 Pin
Ultrasonic Sensor VCC 5V
Ultrasonic Sensor GND GND
Ultrasonic Sensor TRIG GPIO39
Ultrasonic Sensor ECHO GPIO38
Servo Motor GND (Brown/Black) GND
Servo Motor VCC (Red) 5V
Servo Motor Signal (Yellow/Orange) GPIO12

Jumper wires are good for a quick test, but not for a final build. A Screw Terminal Block for ESP32 S3 solves this. Plug the ESP32 S3 into it and screw the wires in. The pins do not change. Just connect each wire to the matching screw terminal:

The wiring diagram between ESP32 S3 Ultrasonic Sensor Servo Motor Screw Terminal

This image is created using Fritzing. Click to enlarge image

A GPIO Breakout Board for ESP32 S3 works too. Besides one S, 3.3V and GND pin for each GPIO, it has extra 3.3V and 5V pins:

The wiring diagram between ESP32 S3 Ultrasonic Sensor Servo Motor GPIO Breakout Board

This image is created using Fritzing. Click to enlarge image

ESP32 S3 Code - Ultrasonic Sensor Controls Servo Motor

The following code uses the ESP32 S3 to read the distance measured by the HC-SR04 ultrasonic sensor and translate it into a servo motor angle. When an object comes within the defined threshold distance, the ESP32 S3 commands the servo to rotate to 90°; when the object moves beyond that threshold, the servo returns to 0°. The ESP32Servo library handles PWM signal generation for the servo, while the ultrasonic measurement is driven directly by pulseIn() for simplicity and low latency.

/* * This ESP32 S3 code was developed by newbiely.com * * This ESP32 S3 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp32-s3/esp32-s3-ultrasonic-sensor-servo-motor */ /* * This ESP32-S3 code is created by esp32io.com * * This ESP32-S3 code is released in the public domain * * For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-s3-ultrasonic-sensor-servo-motor */ #include <ESP32Servo.h> #define TRIG_PIN 39 // ESP32-S3 pin GPIO39 connected to Ultrasonic Sensor's TRIG pin #define ECHO_PIN 38 // ESP32-S3 pin GPIO38 connected to Ultrasonic Sensor's ECHO pin #define SERVO_PIN 12 // ESP32-S3 pin GPIO12 connected to Servo Motor's pin #define DISTANCE_THRESHOLD 50 // centimeters Servo servo; // create servo object to control a servo // variables will change: float duration_us, distance_cm; void setup() { Serial.begin (9600); // initialize serial port pinMode(TRIG_PIN, OUTPUT); // set ESP32-S3 pin to output mode pinMode(ECHO_PIN, INPUT); // set ESP32-S3 pin to input mode servo.attach(SERVO_PIN); // attaches the servo on pin GPIO12 to the servo object servo.write(0); } void loop() { // generate 10-microsecond pulse to TRIG pin digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // measure duration of pulse from ECHO pin duration_us = pulseIn(ECHO_PIN, HIGH); // calculate the distance distance_cm = 0.017 * duration_us; if (distance_cm < DISTANCE_THRESHOLD) servo.write(90); // rotate servo motor to 90 degree else servo.write(0); // rotate servo motor to 0 degree // print the value to Serial Monitor Serial.print("distance: "); Serial.print(distance_cm); Serial.println(" cm"); delay(500); }

Detailed Instructions

  1. New to ESP32 S3? Complete our Getting Started with ESP32 S3 guide first.
  2. Wire the components: Follow the wiring diagram shown above to connect the HC-SR04 ultrasonic sensor and servo motor to your ESP32 S3.
  3. Connect ESP32 S3: Use a USB Type-C cable to connect the board to your computer.
  4. Setup Arduino IDE: If this is the first time you use ESP32 S3, see how to setup environment for ESP32 S3 on Arduino IDE.
  5. Select your board: Choose the ESP32 S3 board and its COM port under Tools in Arduino IDE.
  6. Install ESP32Servo library: Click the Libraries icon on the left bar of the Arduino IDE. Type ESP32Servo in the search box, then look for the servo library by Kevin Harrington, John K. Bennett. Click Install to install the servo motor library for ESP32.
ESP32 S3 servo motor library
  1. Upload the code: Copy the code above and paste it into Arduino IDE, then click the Upload button.
Arduino IDE Upload Code
  1. Open Serial Monitor: Open the Serial Monitor at 9600 baud to see live distance readings and servo angle updates.
  2. Test the sensor: Move your hand in front of the ultrasonic sensor and observe the servo motor responding to changes in distance.
  3. Pro Tip: If the servo twitches erratically, add a small capacitor (100–470 µF) across the servo's power rails to filter voltage spikes and stabilize the signal.

Serial Monitor Output

Open the Serial Monitor at 9600 baud after uploading. You will see output similar to the following as you move your hand in front of the sensor:

∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32S3 Dev Module
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32S3 Dev Module' on 'COM15')
New Line
9600 baud
2026-06-16 09:14:22 -> Distance: 32.4 cm | Servo angle: 0° 2026-06-16 09:14:23 -> Distance: 18.7 cm | Servo angle: 0° 2026-06-16 09:14:24 -> Distance: 9.2 cm | Servo angle: 90° 2026-06-16 09:14:25 -> Distance: 6.5 cm | Servo angle: 90° 2026-06-16 09:14:26 -> Distance: 24.1 cm | Servo angle: 0°
Ln 11, Col 1
ESP32S3 Dev Module on COM15
2

Application Ideas

Combining the ESP32 S3 with an ultrasonic sensor and servo motor unlocks a broad set of proximity-aware actuation projects across automation, robotics, and everyday maker scenarios. Here are some practical ideas to get you started:

  1. Automatic door or gate: Use the servo to swing a barrier open when a person or vehicle is detected within a set range, and close it automatically when they move away.
  2. Touchless trash can lid: Trigger the servo to lift a lid when a hand is sensed close to the bin, enabling hands-free waste disposal.
  3. Proximity-activated robotic arm: Extend or retract a robotic arm joint when an object enters a defined zone, without any button press required.
  4. Parking barrier: Build a servo-driven parking gate that raises automatically when a car approaches the sensor threshold.
  5. Object-avoidance mechanism: Use the distance reading to steer a servo-mounted wheel or rudder away from nearby obstacles in a mobile robot.
  6. Alarm latch: Physically engage or disengage a servo-driven locking pin when someone is detected within a security perimeter.

Video Tutorial

Watch the step-by-step video walkthrough for this ESP32 S3 project below.

Challenge Yourself

Now that your ESP32 S3 ultrasonic-sensor-servo circuit is working, try these progressively harder challenges to deepen your understanding of distance sensing and servo actuation:

  1. Beginner: Change the distance threshold in the code and observe how the servo's trigger point shifts — experiment with values between 5 cm and 50 cm.
  2. Beginner: Modify the code so the servo rotates to 180° instead of 90° when an object is detected close to the sensor.
  3. Intermediate: Add an LED indicator to the ESP32 S3 that turns on when the servo is at 90° and off when it returns to 0°, giving a visual status cue alongside the motor movement.
  4. Intermediate: Implement distance-proportional servo control, where the servo angle is mapped continuously to the measured distance rather than switching between two fixed positions.
  5. Advanced: Add an OLED display to the ESP32 S3 that shows both the real-time distance in centimeters and the current servo angle on screen simultaneously.
  6. Advanced: Build a multi-zone system with two ultrasonic sensors covering different directions, each independently triggering its own servo when an object enters its zone.

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!