ESP32 S3 - Motion Sensor - Relay

This tutorial shows you how to use the ESP32 S3 with an HC-SR501 PIR motion sensor and a relay module to automatically switch a high-voltage device on and off based on detected motion. By the end, you will have a solid foundation for building real-world automation projects such as motion-activated lights, alarms, and security systems with your ESP32 S3.

What you'll build:

  1. A circuit connecting an HC-SR501 motion sensor and relay module to the ESP32 S3
  2. A sketch that activates the relay when motion is detected and deactivates it when the area clears
  3. A system that can switch high-voltage loads like lamps, sirens, or fans via the relay
  4. A foundation for extending into smart-home automation and security projects

We can extend this tutorial to use the motion sensor to control an LED strip, siren, light bulb, or actuator by connecting them to the relay.

Overview of Motion Sensor and Relay

The HC-SR501 PIR motion sensor and relay module are two of the most practical building blocks for automated ESP32 S3 control projects. The HC-SR501 outputs a digital HIGH signal whenever it detects movement from a warm object such as a person or animal, while the relay allows the ESP32 S3 to safely switch high-voltage or high-current loads that would otherwise damage the board's GPIO pins directly.

Key Specifications

We have dedicated tutorials covering each component in depth. Each tutorial contains detailed information and step-by-step instructions about hardware pinout, working principle, wiring connection to the ESP32 S3, and Arduino code. Learn more about them at the following links:

Wiring Diagram

Connect the HC-SR501 motion sensor and relay module to your ESP32 S3 by following the diagram below. The sensor requires a 5V supply for reliable operation, so use the 5V rail on the ESP32 S3 rather than the 3.3V rail.

The wiring diagram between ESP32 S3 Motion Sensor Relay

This image is created using Fritzing. Click to enlarge image

Want a cleaner and safer setup? Try a Screw Terminal Block for ESP32 S3: the ESP32 S3 sits on it, and each pin gets its own screw terminal. The pins do not change. Just connect each wire to the matching screw terminal:

The wiring diagram between ESP32 S3 Motion Sensor Relay Screw Terminal

This image is created using Fritzing. Click to enlarge image

You can also use a GPIO Breakout Board for ESP32 S3. It gives each GPIO its own S, 3.3V and GND pins, so module wires plug straight in:

The wiring diagram between ESP32 S3 Motion Sensor Relay GPIO Breakout Board

This image is created using Fritzing. Click to enlarge image

Safety Notes

Always power the HC-SR501 from the 5V pin of the ESP32 S3, never from 3.3V, as insufficient supply voltage leads to erratic or no detection. On the relay side, verify that the COM and NO (or NC) terminals are securely fastened and that no bare wires are exposed before applying power — keep the high-voltage load wiring physically separated from the low-voltage control wiring to reduce the risk of accidental contact.

Component Pin ESP32 S3 Pin
HC-SR501 VCC 5V
HC-SR501 GND GND
HC-SR501 OUTPUT GPIO42
Relay DC- GND
Relay DC+ 5V
Relay IN GPIO9

Initial Sensor Settings

Before using the HC-SR501, configure these settings for optimal performance during initial testing.

ESP32 S3 motion sensor initial setting
Setting Configuration
Detection Range Adjuster Fully screw clockwise (minimum range for testing)
Time Delay Adjuster Fully screw counter-clockwise (minimum delay)
Repeat Trigger Selector Position jumper as shown in image above

ESP32 S3 Code

The following code reads the HC-SR501 motion sensor output connected to the ESP32 S3 and controls a relay accordingly — activating the relay when motion is detected and deactivating it when the area becomes clear. State transitions are tracked from loop to loop so the relay responds only to changes in motion state rather than continuously toggling.

/* * 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-motion-sensor-relay */ // MotionSensorRelay.cpp // ESP32-S3 - Motion sensor (HC-SR501) controls a relay // Wiring: HC-SR501 OUTPUT -> GPIO42, Relay IN -> GPIO9 #define SENSOR_PIN 42 // HC-SR501 OUTPUT (was D5) #define RELAY_PIN 9 // Relay IN (was D7) int lastState = LOW; void setup() { Serial.begin(115200); pinMode(SENSOR_PIN, INPUT); pinMode(RELAY_PIN, OUTPUT); digitalWrite(RELAY_PIN, LOW); // Ensure relay is off delay(100); Serial.println("[INFO] MotionSensorRelay initialized."); } void loop() { int state = digitalRead(SENSOR_PIN); if (state != lastState) { if (state == HIGH) { digitalWrite(RELAY_PIN, HIGH); // Turn relay on Serial.println("[INFO] Motion detected - Relay: ON"); } else { digitalWrite(RELAY_PIN, LOW); // Turn relay off Serial.println("[INFO] Motion stopped - Relay: OFF"); } lastState = state; } delay(50); }

Detailed Instructions

  1. New to ESP32 S3? Complete our Getting Started with ESP32 S3 guide first.
  2. Wire the components following the wiring diagram shown above.
  3. Connect the ESP32 S3 board to your PC using a USB Type-C cable.
  4. Open Arduino IDE on your PC.
  5. Select the correct ESP32 S3 board and COM port from the Tools menu.
  6. Copy the above code and paste it into Arduino IDE.
  7. Click the Upload button to compile and upload the code to the ESP32 S3.
Arduino IDE Upload Code
  1. Move your hand in front of the HC-SR501 sensor.
  2. Observe the relay activating (you will hear a click) when motion is detected.
  3. Stop moving and observe the relay deactivating after the sensor's time delay expires.
  4. Pro Tip: Open the Serial Monitor at 115200 baud to view motion detection and relay state messages in real time — this makes it much easier to debug unexpected behavior or fine-tune the sensor's sensitivity and delay potentiometers.

Serial Monitor Output

The following Serial Monitor output shows the ESP32 S3 responding to motion detection and clearance events in real time. Each line is timestamped so you can verify the timing between detection and relay activation.

∞
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] Motion detected - Relay: ON [2026-06-16 09:14:30] Motion stopped - Relay: OFF [2026-06-16 09:14:45] Motion detected - Relay: ON [2026-06-16 09:14:53] Motion stopped - Relay: OFF
Ln 11, Col 1
ESP32S3 Dev Module on COM15
2

Application and Project Ideas

Once you master motion-controlled relay switching with the ESP32 S3, you can extend this pattern into a wide range of practical automation and smart-home projects.

  1. Automatic room lighting: Turn on a lamp or LED strip when someone enters a room and switch it off automatically after they leave.
  2. Motion-activated alarm: Trigger a 12V siren or warning light when the sensor detects an intruder outside business hours.
  3. Energy-saving office system: Automatically cut power to monitors, fans, or coffee machines when no motion is detected for a set period.
  4. Smart staircase light: Activate stairway lighting when someone begins climbing and turn it off shortly after they reach the top.
  5. Garage door alert: Use the relay to sound a buzzer whenever motion is detected near a vehicle or entry point.
  6. Greenhouse automation: Activate a ventilation fan whenever a technician enters the growing area, ensuring fresh air circulation on demand.

Relay vs MOSFET Module

A relay is not the only way to switch a device. If your device runs on DC power, such as a 12V LED strip, a 12V solenoid lock or a 12V fan, a MOSFET module can do the same job.

Relay MOSFET Module
What it can do turn the device on or off turn the device on or off, and set its power (PWM)
Noise when switching a click every time no sound
How fast it switches slow, a few milliseconds very fast
Life the contacts wear out after many switches nothing moves, so it lasts long
Type of power AC or DC DC only
Device power supply any voltage the relay is rated for about 6V or more
Isolation from the ESP32 S3 yes, between coil and contacts yes, by the PC817 optocoupler
Good for AC devices, or a simple ON/OFF DC devices, or dimming and speed control

Both the relay and the MOSFET module turn on when the ESP32 S3 pin is HIGH. The 3.3V level of the ESP32 S3 is plenty, because the LED in the PC817 optocoupler needs only a few milliamps. So for a simple ON/OFF, the code above stays the same. Only the wiring changes. For AC mains devices, always use the relay.

To learn the MOSFET module pinout, wiring, PWM code and safety tips, see the ESP32 S3 - MOSFET Module tutorial.

Video Tutorial

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

Challenge Yourself

Now that you can control a relay with a motion sensor on the ESP32 S3, try these progressively challenging extensions to deepen your understanding and build more capable projects.

  1. Beginner: Add an LED indicator that lights up alongside the relay so you have a visual confirmation of motion detection without listening for the relay click.
  2. Beginner: Modify the code to print the total count of motion events to the Serial Monitor each time a new detection occurs.
  3. Intermediate: Implement a minimum ON time so the relay stays active for at least 10 seconds after motion is detected, even if the sensor clears sooner.
  4. Intermediate: Add a second HC-SR501 sensor to cover a wider area, activating the relay only when either sensor detects motion.
  5. Advanced: Add a real-time clock module and restrict relay activation to specific hours, effectively creating a timed motion-activated security system.
  6. Advanced: Extend the project with WiFi so the ESP32 S3 sends an email or push notification whenever the relay is activated by motion.

※ 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!