Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
BETTESWORTHConstruction
Arduino

Automatic Gate Open and Close Using an Ultrasonic Sensor

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Yes, an Arduino, HC-SR04 ultrasonic sensor and servo can open and close a small demonstration gate. The sensor measures distance, the controller detects an approaching object, and a state-based program commands the gate to open, remain open while the area is occupied, then close when the path is clear.

That setup is suitable for a model gate, classroom project or low-voltage prototype. It is not a complete safety system for a full-size vehicle gate. For a residential or commercial installation, the Arduino should only provide an isolated convenience or access signal to a properly specified gate operator. Entrapment protection must come from compatible monitored photoelectric beams, safety edges, force-reversal protection and position controls—not from one ultrasonic sensor.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the gate system before choosing the sensor

The mechanical gate determines whether this project is appropriate:

Gate type Suitable approach
Model or classroom gate Arduino, HC-SR04, hobby servo, LEDs and a lightweight frame.
Small pedestrian swing gate A purpose-built low-voltage actuator or servo may be suitable after checking load, travel and safety requirements.
Residential swing gate Use a listed swing-gate operator with limit controls, safety inputs and suitable entrapment protection.
Residential slide gate Use a rack-and-pinion or chain-drive operator designed for the gate’s weight, length, track and duty cycle.
Commercial or public vehicle gate Do not treat an Arduino-only build as an appropriate controller. Use specified commercial equipment and qualified installation.

Published Arduino examples commonly use an Uno, SG90 servo, LEDs and HC-SR04 to demonstrate a small automatic gate. That is a useful learning architecture, but a micro-servo moving a model panel is not equivalent to driving a steel, timber or aluminium vehicle gate.

Popular on Amazon
WWZMDiB 2 Pcs HC-SR04 Ultrasonic Sensor Module Compatible with for Arduino R3 MEGA Mega2560 Duemilanove Nano Robot XBee ZigBee (2 Pcs HC-SR04 Ultrasonic Sensor)
  • HC-SR04 Ultrasonic Sensor:This is a device that can use sound waves to measure the distance of an object. It measures distance by emitting a sound wave of a specific frequency and listening to the bounce of that sound wave. The distance between the sonar sensor and the object can be calculated by recording the time elapsed between the generation of the sound wave and the bounce of the sound wave
  • Working Voltage: 5V DC;Quiescent current: less than 2mA
  • Ranging Distance:2cm - 450 cm;High precision: 0.3 cm
  • Effectual Angle: <15°
  • Test mode :Test distance = ((Duration of high level)*(Sonic :340m/s))/2

See the Arduino Project Hub demonstration.

How the automatic gate works

Object approaches
↓
HC-SR04 measures distance
↓
Arduino filters and validates readings
↓
Servo moves a model gate, or an isolated interface requests opening
↓
Open → hold open → verify clear → close

The HC-SR04 sends an ultrasonic pulse and measures the returning echo. The Arduino converts the echo time into distance. A reliable prototype should not make a decision from one reading or from a single statement such as if (distance < threshold). It should use repeated readings, invalid-reading handling, debounce timing, separate detection and clear thresholds, movement timeouts and explicit operating states.

Arduino provides an HC-SR04-compatible library and documentation. The pin assignments below can also be handled with direct pulse measurement.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Parts list

For a low-voltage demonstration gate

  • Arduino Uno or compatible board.
  • HC-SR04 ultrasonic sensor.
  • Small servo, such as an SG90, for a lightweight model gate.
  • External 5 V supply for the servo where required.
  • Gate frame, hinge, linkage and mechanical stops.
  • LED or buzzer for status indication.
  • Push button for manual open, close or reset.
  • Jumper wires, breadboard and suitable enclosure or mounting bracket.

For connecting to an existing full-size operator

  • An installed gate operator correctly selected for the gate’s size, mass, wind exposure and duty cycle.
  • An isolated relay, optocoupler or manufacturer-approved accessory interface.
  • Compatible monitored photoelectric sensors and, where required, safety edges.
  • Limit switches, encoders or the operator’s own position feedback.
  • Emergency stop, manual release and suitable power-failure provisions.

Do not buy a hobby ultrasonic sensor as though it were a life-safety device. For a real gate, the operator, monitored safety equipment and installation method matter more than the Arduino trigger.

Wiring the HC-SR04 to an Arduino Uno

HC-SR04 pin Arduino Uno connection
VCC 5 V
GND GND
TRIG Digital pin 2
ECHO Digital pin 4

The trigger pin is an Arduino output and the echo pin is an input. Pin numbers are not special; they can be changed in the sketch. The Arduino Project Hub example uses trigger pin 2 and echo pin 4.

A typical direct measurement routine is:

digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);

digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000UL);
float distanceCm = duration * 0.0343f / 2.0f;

The timeout is essential. Without it, a missing echo can leave the program waiting. Treat a timeout as unknown, not automatically as “the path is clear.” If using an ESP32 or another 3.3 V board, check the exact board documentation and protect the echo line with suitable level shifting or a divider where required. Do not assume a 5 V echo signal is safe for every GPIO.

Also popular on Amazon
ELEGOO 5PCS HC-SR04 Ultrasonic Module Distance Sensor Kit | Compatible with Arduino UNO MEGA Nano Robot XBee ZigBee, Measure 3-450 cm, Obstacle Avoidance, Parking Alerts, STEM Projects
  • NON-CONTACT DISTANCE SENSING: Add object detection to robot navigation, parking-distance prototypes, automatic lids, counters and interactive projects; each HC-SR04 uses a 40 kHz ultrasonic burst and echo timing to estimate distance
  • 5-PACK FOR REPEATABLE PROTOTYPING: Use multiple HC-SR04 modules across builds, compare sensor positions or keep spares for testing and replacement; each module integrates an ultrasonic transmitter, receiver and control circuit
  • 5 V MODULE WITH 3-450 CM RANGE: Connect VCC, Trig, Echo and GND, use a 10 µs trigger pulse and measure Echo duration; resolution is 0.3 cm with an effective angle under 15°, while the controller board and external power source are not included
  • PROTECT 3.3 V GPIO: The HC-SR04 operates from 5 V and its Echo output is 5 V, so use a voltage divider or suitable level shifting with 3.3 V inputs; keep the module dry and use it for prototyping rather than calibrated measurement
  • FOR ROBOTICS & STEM PROJECTS: Suitable for distance measurement, object detection, automatic lids, parking alerts, robot navigation and other hands-on electronics builds

Wiring the servo safely

Connect the servo signal wire to the selected control pin and connect the servo supply to a source capable of delivering its current, including startup and stall current. Small servos can reset an Arduino when powered from an inadequate supply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Use an external supply when the servo load requires it.
  • Connect the external supply ground to the Arduino ground.
  • Keep the linkage within the servo’s mechanical travel.
  • Use physical stops rather than forcing the servo against the gate frame.
  • Do not use a hobby servo for a full-size gate panel.

Arduino prototype with filtering, hysteresis and fault handling

The following sketch is for a small, low-energy demonstration gate. It assumes that the servo reaches its commanded position after a timed interval. That assumption is acceptable only for a simple model. A real gate must use actual limit or position feedback.

#include <Servo.h>

const byte TRIG_PIN = 2;
const byte ECHO_PIN = 4;
const byte SERVO_PIN = 9;

const int CLOSED_ANGLE = 0;
const int OPEN_ANGLE = 90;

const float APPROACH_CM = 60.0;
const float CLEAR_CM = 90.0;

const unsigned long SENSOR_INTERVAL_MS = 80;
const unsigned long OPEN_HOLD_MS = 5000;
const unsigned long MOVE_TIMEOUT_MS = 4000;
const unsigned long DETECT_DEBOUNCE_MS = 300;

Servo gate;

enum GateState { CLOSED, OPENING, OPEN, CLOSING, FAULT };
GateState state = CLOSED;

unsigned long lastSensorMs = 0;
unsigned long stateStartedMs = 0;
unsigned long lastPresenceMs = 0;
unsigned long detectionStartedMs = 0;
float distanceCm = -1.0;

float readDistanceCm() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000UL);
if (duration == 0) return -1.0;
return duration * 0.0343f / 2.0f;
}

bool objectPresent() {
return distanceCm > 0 && distanceCm <= APPROACH_CM;
}

bool areaClear() {
return distanceCm >= CLEAR_CM;
}

void enterState(GateState next) {
state = next;
stateStartedMs = millis();
}

void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
gate.attach(SERVO_PIN);
gate.write(CLOSED_ANGLE);
enterState(CLOSED);
}

void loop() {
unsigned long now = millis();

if (now - lastSensorMs >= SENSOR_INTERVAL_MS) {
lastSensorMs = now;
distanceCm = readDistanceCm();

Serial.print("Distance: ");
Serial.println(distanceCm);

if (objectPresent()) {
lastPresenceMs = now;
if (detectionStartedMs == 0) detectionStartedMs = now;
} else {
detectionStartedMs = 0;
}
}

switch (state) {
case CLOSED:
if (detectionStartedMs != 0 &&
now - detectionStartedMs >= DETECT_DEBOUNCE_MS) {
gate.write(OPEN_ANGLE);
enterState(OPENING);
}
break;

case OPENING:
if (now - stateStartedMs >= MOVE_TIMEOUT_MS) {
enterState(FAULT);
break;
}
if (now - stateStartedMs >= 1000) {
enterState(OPEN);
lastPresenceMs = now;
}
break;

case OPEN:
if (objectPresent()) lastPresenceMs = now;
if (now - lastPresenceMs >= OPEN_HOLD_MS) {
gate.write(CLOSED_ANGLE);
enterState(CLOSING);
}
break;

case CLOSING:
if (objectPresent()) {
gate.write(OPEN_ANGLE);
enterState(OPENING);
break;
}
if (now - stateStartedMs >= MOVE_TIMEOUT_MS) {
enterState(FAULT);
break;
}
if (now - stateStartedMs >= 1000) enterState(CLOSED);
break;

case FAULT:
// Stop issuing movement commands.
break;
}
}

What the sketch is doing

  • Closed: requires a detected object to remain within the approach range for the debounce period.
  • Opening: limits the maximum movement time instead of waiting forever.
  • Open: resets the hold timer while presence remains detected.
  • Closing: reopens if an object is detected during the closing cycle.
  • Fault: stops automatic movement after a timeout rather than retrying indefinitely.
  • Hysteresis: uses 60 cm for approach detection and 90 cm for a clear indication, reducing rapid open-close oscillation.

The prototype still has important limitations. It does not calculate a median filter, it assumes timed servo travel, and an invalid ultrasonic reading can never prove that a full-size gate path is safe. For a more robust prototype, collect several valid readings and use their median or moving average before changing state.

Why ultrasonic sensing is not enough for a real gate

An HC-SR04 detects distance; it does not provide complete entrapment protection. Readings can fail or become unstable because of:

  • Angled vehicle panels reflecting sound away from the receiver.
  • Soft, irregular or narrow objects producing weak echoes.
  • Rain, wind and temperature changes.
  • Reflections from walls, posts or the gate itself.
  • A person, pet, bicycle wheel or limb moving outside the sensor’s narrow field of view.
  • Multiple ultrasonic sensors interfering if triggered at the same time.

For these reasons, use an ultrasonic sensor as an approach or convenience trigger in a prototype. It should not be the only device expected to detect a child, pet, vehicle or limb in every pinch and shear zone.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Also popular on Amazon
MTDELE 5 Pcs HC-SR04 Ultrasonic Sensor Module with 5Pcs Mounting Bracket | Compatible with for Arduino R3 UNO MEGA XBee Nano Robot
  • HC-SR04 Ultrasonic Sensor:Compatible with for Arduino R3 UNO MEGA Mega2560 Duemilanove XBee Nano Robot With 5Pcs mounting bracket
  • Working Voltage: 5V DC; Quiescent current: Less than 2mA
  • Ranging Distance:2 - 450 cm;High precision:0.3 cm;Effectual Angle: < 15°
  • Test distance=((high level duration)*(sound wave: 340m/s))/2
  • Merchandise included:5Pcs HC-SR04 Ultrasonic Sensor;5Pcs Mounting bracket;20Pcs Mounting screw;10Pcs Female to Female Wire; 10Pcs Male to Female Wire

Commercial gate systems may use:

  • Photoelectric beams: detect interruption across a defined opening or danger zone.
  • Safety edges: detect physical contact at a protected edge.
  • Inherent-reverse protection: detects excessive resistance or force.
  • Limit switches or encoders: confirm fully open and fully closed positions.
  • Warning lights, audible alarms and signage.
  • Emergency release and manual operation.

Ubiquiti’s gate documentation describes monitored photoelectric entrapment protection, while HySecurity’s UL 325 guidance discusses monitored photo eyes and edge sensors.

Testing procedure for the prototype

  1. Test the sensor alone. Confirm distances in the Serial Monitor and check that timeouts are reported as invalid.
  2. Test the servo without the gate load. Confirm the open and closed angles and check for resets or overheating.
  3. Attach the lightweight gate. Check that the linkage does not bind at either endpoint.
  4. Test detection debounce. Move an object in and out of the sensing area and confirm that the gate does not oscillate.
  5. Test the hold-open behavior. Keep an object in the area and verify that the gate does not close after the initial timer expires.
  6. Test interruption while closing. Use a safe test object and verify that the prototype reopens.
  7. Test sensor failure. Disconnect or block the sensor and verify that the controller does not interpret every invalid reading as clear.
  8. Test power loss and restart. Confirm the gate’s known startup position and manual recovery procedure.
  9. Enable automatic closing only after all previous tests pass.

For a real gate, also test the operator’s limits, reversal force, emergency stop, photo eyes, safety edges, manual release and power-failure behavior in accordance with the manufacturer instructions.

Connecting an Arduino to a real gate operator

The safest general architecture is:

Ultrasonic approach sensor
↓
Arduino or low-voltage controller
↓
Isolated relay, dry contact or approved interface
↓
Gate operator OPEN input

The Arduino should normally act as an isolated accessory input—not as a replacement for the operator’s motor controller.

  • Read the operator manual before making any connection.
  • Confirm whether the input expects a dry contact, normally open contact, normally closed contact, pulse, maintained signal or a particular voltage.
  • Use a properly rated relay, optocoupler or manufacturer-approved interface.
  • Never connect an Arduino GPIO directly to mains voltage, motor leads, a battery motor circuit or an unknown terminal.
  • Keep low-voltage and high-voltage wiring separated.
  • Have a qualified gate technician perform work on a vehicle gate.

An operator may refuse to run unless its required monitored safety devices are connected. A DoorKing operator document illustrates the kinds of model-specific requirements that can include monitored entrapment devices, dedicated terminals and control-location restrictions. The exact operator manual always takes precedence.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

UL 325 and installation responsibility

UL 325 covers automatic gate operators and related systems, including slide, swing, pivot, vertical-lift, barrier-arm and bifold gates. UL Solutions states that the 2024 IBC, IRC, IFC, NFPA 1 and NFPA 101 require listed gate operators in the circumstances covered by those codes.

Also popular on Amazon
AEDIKO 10pcs HC-SR04 Ultrasonic Module Distance Sensor with Wire Cable
  • HC-SR04 Ultrasonic Distance Sensor: Power Supply: 5V DC; Quiescent Current : <2mA; Effectual Angle: <15°; Detection Distance: 2 - 500cm; Resolution: 0.3cm
  • All in One Designed: HC-SR04 Consists of Ultrasonic Transmitter, Receiver, and Control Circuit;When Trigged it Sends Out a Series of 40KHz Ultrasonic Pulses and Receives Echo from an Object.
  • Easy to Install: HC-SR04 Ultrasonic Distance Sensor with 4 Pins: VCC; Trig(Control Side); Echo (Receiver); Out (Empty); GND; Small Size Designed,Easy for Embedded Installation.
  • Applications: HC-SR04 Ultrasonic Distance Sensor Widely used for Robot Obstacle Avoidance, Object Distance Measuring, Liquid Level Detection, Public Security, Parking Lot Detection etc.
  • Package Contents: You will Get 10pcs HC-SR04 Ultrasonic Distance Sensor,1pc 10pin Cable 20cm(M-F) and 1pc 10pin Cable 20cm(F-F)

Read the UL Solutions overview of gate operators and code references and the CPSC background on gate-operator safety. Requirements vary by jurisdiction, gate type, installation context and adopted code edition, so do not infer compliance from a generic product description.

For a full-size powered gate:

  • Keep children and pets away from the moving area.
  • Ensure the gate is visible from the control point.
  • Provide an emergency stop or disconnect where appropriate.
  • Provide a manual release and document how it works during a power failure.
  • Test opening, closing, reversal, obstruction detection and restart behavior.
  • Use the manufacturer’s approved safety devices and wiring.
  • Do not enable automatic closing until the mechanical movement and safety inputs have been verified.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting

The sensor always reads zero or invalid

Check VCC, ground, trigger and echo wiring. Confirm that the trigger pulse is approximately 10 microseconds and that the timeout is long enough for the intended range. Test a large flat target directly in front of the sensor.

The readings are unstable

Mount the sensor rigidly, aim it away from walls and the moving gate, increase the interval between readings and filter multiple samples. Test different target angles and surfaces. Outdoor wind, rain and temperature changes can reduce consistency.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The gate opens repeatedly

Check whether the sensor is detecting the gate frame or a nearby wall. Increase the detection debounce period, add hysteresis and review the sensor’s mounting height and direction.

The gate closes too soon

Do not use one fixed delay as proof that the area is clear. Extend the hold timer, require persistent clear readings and use a separate passage sensor where appropriate. A single HC-SR04 may not know whether a vehicle has fully cleared the gate.

Also popular on Amazon
HC-SR04P Ultrasonic Distance Sensor Module with 3V to 5.5V Wide Voltage, 2cm–450cm Range, 4-Pin Interface Compatible with Arduino and Raspberry Pi (2-pcs)
  • Measures distances from ‌2cm to 450cm‌ with ±3mm accuracy using high-frequency ultrasonic pulses and optimized echo detection circuitry
  • Wide voltage support (3V–5.5V)‌ enables seamless integration with 3.3V microcontrollers like Raspberry Pi and ESP32, eliminating the need for voltage level conversion
  • 4-pin digital interface‌ (VCC, GND, TRIG, ECHO) allows direct connection to Arduino-compatible boards, STM32, and other MCUs with no additional components required
  • High refresh rate up to 50Hz‌ ensures real-time feedback for dynamic applications such as robotic navigation and automated door systems
  • Low-power design‌ draws under 15mA during active measurement

The servo resets the Arduino

Use a suitable external servo supply, size it for startup and stall current, add common ground and keep motor wiring separate from signal wiring.

The real operator ignores the command

Check whether the operator expects a dry contact, pulse or maintained input. Verify relay contact type, terminal assignment and required safety devices. Never guess from wire colour or connect directly to motor terminals.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The ESP32 behaves unpredictably

Check the HC-SR04 echo voltage against the specific ESP32 board’s GPIO limits. A 5 V echo output may require level protection. Confirm that the chosen GPIO is suitable for input use.

Alternative sensors and access methods

Approach Best use Important limitation
HC-SR04 and Arduino Model gate or experimental approach trigger Not a standalone safety system.
Photoelectric beam Defined passage or entrapment zone Requires alignment, weather protection and operator compatibility.
Safety edge Physical contact detection at a gate edge Does not cover every entrapment area.
Vehicle loop detector Vehicle presence at a driveway Requires a suitable installed loop or wireless equivalent.
RFID, keypad or remote Authorised access Does not itself provide obstruction protection.
Commercial smart gate controller Managed access and compatible operator integration Requires ecosystem and compatibility checks.

Prototype versus real-gate buying decisions

Low-cost prototype

Use an Arduino-compatible board, HC-SR04, small servo, breadboard, wiring and an external supply. This is the right level for learning the sensor and state-machine logic.

Retrofit to an existing operator

Use the existing listed operator, an approved isolated trigger interface and compatible monitored photoelectric devices. Confirm all terminals and operating modes from the operator manual.

Professional vehicle-gate installation

Specify a complete operator listed for the gate’s dimensions, weight, duty cycle and exposure. Include monitored entrapment devices, position feedback, manual release, power-failure provisions and qualified installation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For compatible access-control installations, manufacturer documentation such as Ubiquiti’s Gate Hub guidance shows why the access controller, operator and entrapment devices must be treated as one compatible system.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.