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.
| Net | Pins |
|---|---|
| GND | A1 GNDD2 KQ1 EU2 GNDV1 −V2 − |
| 5V | A1 5VD1 KK1 A1U2 VCCV1 + |
| 12V | K1 COMV2 + |
| BASE | Q1 BR1 2 |
| COIL | D1 AK1 A2Q1 C |
| DRV | A1 D4R1 1 |
| ECHO | A1 D8U2 ECHO |
| LAMP | K1 NOR2 1 |
| LED_A | D2 AR2 2 |
| TRIG | A1 D7U2 TRIG |
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