This circuit integrates an HC-SR04 Ultrasonic Sensor with an Arduino UNO microcontroller and a buzzer. The primary function of this circuit is to measure the distance to an object using the ultrasonic sensor and to provide an audible alert when the object is within a certain distance threshold. The Arduino UNO is programmed to trigger the HC-SR04 to send out an ultrasonic pulse and then listen for the echo. The time taken for the echo to return is used to calculate the distance to the object. If this distance is less than 10 centimeters, the buzzer is activated.
/*
* Arduino UNO R3 with HC-SR04 Ultrasonic Sensor and Buzzer
* This code measures the distance using the HC-SR04 sensor and activates the
* buzzer if the distance is below a certain threshold.
*/
#define TRIG_PIN 7
#define ECHO_PIN 6
#define BUZZER_PIN 12
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
long duration, distance;
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = (duration / 2) / 29.1;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance < 10) {
digitalWrite(BUZZER_PIN, HIGH);
} else {
digitalWrite(BUZZER_PIN, LOW);
}
delay(500);
}
The code is written for the Arduino UNO and is responsible for controlling the HC-SR04 Ultrasonic Sensor and the buzzer. The TRIG_PIN
and ECHO_PIN
constants are defined to correspond to the digital pins D7 and D6 on the Arduino, respectively, which are connected to the TRIG and ECHO pins of the HC-SR04. The BUZZER_PIN
is set to D12, which is connected to the buzzer. The setup()
function initializes these pins and starts serial communication. The loop()
function triggers the ultrasonic sensor, calculates the distance, and activates the buzzer if the distance is below 10 centimeters.