This circuit is designed to utilize an Arduino UNO microcontroller to interface with an HC-SR04 Ultrasonic Sensor and a red LED. The purpose of the circuit is to measure the distance of an object from the sensor and indicate the proximity of the object by blinking the LED at a rate proportional to the distance measured. The closer the object, the faster the LED blinks. The Arduino UNO is programmed to send a pulse to the ultrasonic sensor, which then emits an ultrasonic wave. When the wave hits an object, it is reflected back to the sensor. The Arduino calculates the distance based on the time it takes for the echo to return. If the measured distance is below a certain threshold, the LED is activated.
int trigpin=9; // Output pin for triggering ultrasonic pulse
int Echopin=10; // Input pin for receiving ultrasonic echo
int ledpin=13; // Output pin for controlling LED
int threshold_distance=30; // Distance threshold for LED activation (in cm)
long duration;
int distance;
void setup() {
pinMode(trigpin, OUTPUT);
pinMode(Echopin, INPUT);
pinMode(ledpin, OUTPUT);
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
// Trigger ultrasonic pulse
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
// Read echo pulse
duration = pulseIn(Echopin, HIGH);
// Calculate distance from duration
distance = (0.034 * duration) / 2;
Serial.print(distance);
Serial.println("cm");
// Blink LED based on distance
if(distance < threshold_distance) {
int ledblink = map(distance, 0, threshold_distance, 100, 500);
digitalWrite(ledpin, HIGH);
delay(ledblink);
digitalWrite(ledpin, LOW);
delay(ledblink);
} else {
digitalWrite(ledpin, LOW);
}
}
This code is designed to run on the Arduino UNO microcontroller. It initializes the necessary pins, performs distance measurements using the HC-SR04 Ultrasonic Sensor, and blinks the LED at a rate inversely proportional to the measured distance. The serial communication is used for debugging purposes to output the distance measurements to the serial monitor.