deckle studioOpen in the editor

Arduino Uno: distance alarm with relay

HC-SR04 measures; below 20 cm the relay pulls in.

  • Arduino Uno
  • HC-SR04
Open in the simulatorNo account needed: press Simulate and it runs.

How it works

The HC-SR04 ultrasonic sensor measures the distance (set it in the inspector). Below 20 cm, D4 switches relay K1 through transistor Q1, which turns on a 12 V lamp (LED chain). D1 is the flyback diode: without it the collector jumps far above 12 V at turn-off (place a probe on Q1-C and delete D1).

Wiring

Each line is one connection (net) and the pins it joins.

NetPins
GNDA1 GNDD2 KQ1 EU2 GNDV1 −V2 −
5VA1 5VD1 KK1 A1U2 VCCV1 +
12VK1 COMV2 +
BASEQ1 BR1 2
COILD1 AK1 A2Q1 C
DRVA1 D4R1 1
ECHOA1 D8U2 ECHO
LAMPK1 NOR2 1
LED_AD2 AR2 2
TRIGA1 D7U2 TRIG
D2
LED

Parts

Firmware

sketch.ino · 16 lines

// HC-SR04 (TRIG D7, ECHO D8) measures the distance; below 20 cm the relay pulls in (D4 -> transistor)
const int TRIG = 7, ECHO = 8, RELAY = 4;

void setup() {
  Serial.begin(115200);
  pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); pinMode(RELAY, OUTPUT);
}

void loop() {
  digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW);
  unsigned long us = pulseIn(ECHO, HIGH, 30000);
  float cm = us * 0.0343 / 2;
  digitalWrite(RELAY, us > 0 && cm < 20 ? HIGH : LOW);
  Serial.print(F("Distance: ")); Serial.print(cm, 1); Serial.println(F(" cm"));
  delay(100);
}
Open in the simulator

More examples: Arduino