const int trigPin = 2; // Trigger pin of the HC-SR04
const int echoPin = 4; // Echo pin of the HC-SR04
const int ledPin = 13; // Digital pin for the LED
const int maxDistance = 200; // Maximum distance in centimeters for mapping
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// Trigger the HC-SR04 to measure distance
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin and calculate the distance
long duration = pulseIn(echoPin, HIGH);
int distance = duration * 0.034 / 2;
// Map the distance to LED intensity
int brightness = map(distance, 0, maxDistance, 255, 0);
brightness = constrain(brightness, 0, 255);
// Set the LED intensity
analogWrite(ledPin, brightness);
// Print distance and brightness to Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm, Brightness: ");
Serial.println(brightness);
delay(500); // Adjust the delay as needed
}