Devices & Components
Arduino Uno Rev3
10 jumper wires 150mm male
220 ohm resistor
Green LED
Passive Buzzer
HC-SR04 Ultrasonic Sensor
Red LED
Yellow LED
Software & Tools
Arduino Cloud Editor
Project description
Code
Collision Warning System
cpp
Collision Warning System with Distance Sensor
1// Collision Warning System with Distance Sensor (HC-SR04) 2// Author: Ana Rodrigues 3// Oct 2, 2025 4// Object is farther than 50cm: Green LED lights up 5// Object is closer than 50 cm, but more than 10cm away: Yellow LED lights, buzzer plays 300Hz tone 6// Object is closer than 10cm: Red LED lights up, buzzer plays 500Hz tone 7 8//LED pins 9const int greenLED = 2; 10const int yellowLED = 3; 11const int redLED = 4; 12 13// Ultrasonic sensor pins 14const int trigPin = 9; 15const int echoPin = 10; 16 17// Passive buzzer pin 18const int buzzer = 11; 19 20void setup() { 21 pinMode(greenLED, OUTPUT); 22 pinMode(yellowLED, OUTPUT); 23 pinMode(redLED, OUTPUT); 24 pinMode(trigPin, OUTPUT); 25 pinMode(echoPin, INPUT); 26 Serial.begin(9600); 27} 28 29void loop() { 30 // Measure distance 31 digitalWrite(trigPin, LOW); 32 delayMicroseconds(2); 33 digitalWrite(trigPin, HIGH); 34 delayMicroseconds(10); 35 digitalWrite(trigPin, LOW); 36 37 long duration = pulseIn(echoPin, HIGH); 38 long distance = duration * 0.034 / 2; 39 40 Serial.print("Distance: "); 41 Serial.print(distance); 42 Serial.println(" cm"); 43 44 //Error in measurement: 45 if (distance <= 0) 46 return; 47 48 //Too close: 49 if (distance <= 10) { 50 digitalWrite(greenLED, LOW); 51 digitalWrite(yellowLED, LOW); 52 digitalWrite(redLED, HIGH); 53 tone(buzzer, 500); // Play 500Hz tone 54 return; 55 } 56 57 //Midrange: 58 if (distance <= 30) { 59 digitalWrite(greenLED, LOW); 60 digitalWrite(yellowLED, HIGH); 61 digitalWrite(redLED, LOW); 62 tone(buzzer, 300); // Play 300Hz tone 63 return; 64 } 65 66 //Normal status: 67 digitalWrite(greenLED, HIGH); 68 digitalWrite(yellowLED, LOW); 69 digitalWrite(redLED, LOW); 70 noTone(buzzer); // stop buzzer 71 72 delay(100); 73}
Downloadable files
Collision Warning System
Arduino file
collisionWarningSystem.ino
Comments
Only logged in users can leave comments