This circuit is designed to control a 12V power LED using an Arduino Nano in conjunction with an HC-SR04 Ultrasonic Sensor and a single-channel relay module. The LED is turned on or off based on the proximity of an object to the ultrasonic sensor. If the detected distance is less than or equal to a predefined safety distance, the relay switches off the LED, otherwise, the LED remains on. The circuit is powered by a 12V battery.
// Code for controlling a power LED using an HC-SR04 Ultrasonic Sensor and a relay module
const int trigPin = 9;
const int echoPin = 10;
const int relayPin = 8;
const int safetyDistance = 100; // Distance in cm (1 meter)
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, LOW); // Keep LED on initially
Serial.begin(9600);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration * 0.034) / 2;
Serial.print("Distance: ");
Serial.println(distance);
if (distance <= safetyDistance) {
digitalWrite(relayPin, HIGH); // Turn off LED
} else {
digitalWrite(relayPin, LOW); // Keep LED on
}
delay(500); // Delay for stability
}
This code initializes the Arduino Nano to communicate with the HC-SR04 Ultrasonic Sensor and control the relay module. The safetyDistance
variable defines the threshold distance for the relay to switch off the LED. The setup()
function configures the necessary pins and initializes serial communication. The loop()
function continuously measures the distance using the ultrasonic sensor and controls the relay accordingly. If the measured distance is less than or equal to safetyDistance
, the relay is activated, turning off the LED. If the distance is greater, the relay is deactivated, and the LED remains on.