This Arduino project uses an ultrasonic sensor (HC-SR04) to measure the distance to the nearest object. If the object is detected within a certain range, a piezo buzzer will sound a security alarm, alternating between two different tones. Additionally, an LED is activated when the object is within the predefined range.
- Arduino Uno
- HC-SR04 Ultrasonic Sensor
- Piezo Buzzer
- LED
- Jumper Wires
- Breadboard
- VCC: Connect to 5V on Arduino
- GND: Connect to GND on Arduino
- Trig Pin: Connect to Digital Pin 7
- Echo Pin: Connect to Digital Pin 8
- Positive: Connect to Digital Pin 3
- Negative: Connect to GND on Arduino
- Anode (+): Connect to Digital Pin 2 (with a resistor)
- Cathode (-): Connect to GND on Arduino
- The ultrasonic sensor emits a sound wave from its Trig Pin, and the time it takes for the wave to return to the sensor is measured by the Echo Pin.
- The time duration of the returning pulse is used to calculate the distance to the nearest object.
- If an object is detected within a certain range (in this case, less than 200 microseconds), the LED lights up, and the piezo buzzer emits an alternating alarm sound, simulating a security alert.
- If no object is detected within that range, the LED remains off, and the buzzer is silent.
-
Pin Setup:
trigPin = 7andechoPin = 8: Pins for the ultrasonic sensor.buzzerPin = 3: Pin for the piezo buzzer.pinMode(2, OUTPUT): Pin 2 is used to control an LED.
-
Distance Calculation:
- The distance is calculated using the
pulseIn()function, which measures the time it takes for the sound pulse to return to the sensor.
- The distance is calculated using the
-
Alarm Triggering:
- If the measured pulse duration is less than or equal to 200 microseconds, the buzzer and LED are triggered.
-
Buzzer Sound:
- The buzzer alternates between two frequencies (1000 Hz and 600 Hz) with delays in between to create an alarm-like sound.
- Connect the components as per the circuit diagram described above.
- Upload the code to your Arduino board.
- Once uploaded, the sensor will continuously monitor the distance, and the buzzer will sound if an object is within range.
- The LED will also light up if the object is detected within the predefined range.
- You can modify the
if (duration <= 200)condition to change the range at which the alarm is triggered by adjusting the threshold based on your requirements. - The buzzer frequency and duration can also be changed to create different alarm effects.
This project is in the public domain and open for anyone to use and modify.