Step-by-Step Guide to Make a Motion-Activated LED Using Arduino Uno and HC-SR04 SensorMaterials Needed
Read more- Arduino Uno
- HC-SR04 Ultrasonic Distance Sensor
- LED (any color)
- 470Ω Resistor (for the LED)
- Breadboard and jumper wires
Connect the HC-SR04 Distance Sensor:
- VCC to 5V on the Arduino.
- GND to GND on the Arduino.
- Trig to Digital Pin 9 on the Arduino.
- Echo to Digital Pin 10 on the Arduino.
Connect the LED:
- Insert the anode (longer leg) of the LED into Digital Pin 8 on the Arduino through a 470Ω resistor.
- Insert the cathode (shorter leg) of the LED into GND on the Arduino
- Open the Arduino IDE.
- Copy and paste the following code into a new sketch:
// Define pin connections
const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 8;
// Set a distance threshold for detecting movement (in cm)
const int movementThreshold = 20; // Adjust this to your desired distance
void setup() {
// Initialize pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
// Start Serial Monitor for debugging
Serial.begin(9600);
Serial.println("Starting distance sensor...");
}
void loop() {
// Trigger the sensor to send out a pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse
long duration = pulseIn(echoPin, HIGH);
// Calculate distance (in cm)
int distance = duration * 0.034 / 2;
// Print distance to Serial Monitor for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if an object is within the threshold distance
if (distance > 0 && distance <= movementThreshold) {
Serial.println("Object detected within range. Turning LED on.");
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
Serial.println("No object detected or out of range. Turning LED off.");
digitalWrite(ledPin, LOW); // Turn off the LED
}
// Delay to avoid overwhelming the sensor
delay(200);
}
1 / 2
2 projects • 1 follower
Just a nice creator with ideas every now and then.
Comments
Please log in or sign up to comment.