#include <Servo.h> // Include the Servo library
Servo myServo; // Create a Servo object
// Define HC-SR04 pins
const int trigPin = 11; // Trigger pin connected to Arduino pin 11
const int echoPin = 12; // Echo pin connected to Arduino pin 12
// Define fairy lights pin
const int lightsPin = 3; // Connected to the PWM control pin of fairy lights
// Define the threshold distance (in cm)
const int distanceThreshold = 10;
// Fade settings
const int fadeDelay = 5; // Delay between brightness adjustments (in milliseconds)
void setup() {
// Initialize the servo
myServo.attach(9); // Attach the servo to pin 9
myServo.write(0); // Set the servo to 0 degrees initially
// Initialize the HC-SR04 pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize fairy lights pin
pinMode(lightsPin, OUTPUT);
analogWrite(lightsPin, 0); // Start with lights off
// Begin Serial communication for debugging (optional)
Serial.begin(9600);
}
void loop() {
int distance = measureDistance(); // Measure the distance
// Print the distance to Serial Monitor (optional)
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance > 0 && distance <= distanceThreshold) {
// Gradually fade in the lights and start the servo movement
fadeLights(true);
delay(500); // Short delay to sync the fade-in with the servo movement
// Move the servo to 90 degrees and hold for 5 seconds
myServo.write(90);
delay(5000);
// Return the servo to 0 degrees
myServo.write(0);
// Gradually fade out the lights
fadeLights(false);
}
delay(100); // Small delay for stability
}
// Function to measure distance using HC-SR04
int measureDistance() {
// Send a 10 microsecond HIGH pulse to the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the echo time (duration of the HIGH signal in microseconds)
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm (duration / 58 = distance in cm)
int distance = duration / 58;
// Return the distance
return distance;
}
// Function to gradually fade in or fade out the lights
void fadeLights(bool fadeIn) {
if (fadeIn) {
// Gradually increase brightness
for (int brightness = 0; brightness <= 255; brightness++) {
analogWrite(lightsPin, brightness);
delay(fadeDelay); // Adjust fade speed
}
} else {
// Gradually decrease brightness
for (int brightness = 255; brightness >= 0; brightness--) {
analogWrite(lightsPin, brightness);
delay(fadeDelay); // Adjust fade speed
}
}
}
Click to Expand
Content Rating
Is this a good/useful/informative piece of content to include in the project? Have your say!
You must login before you can post a comment. .