// Write a program for check the distanace by using ultrasonic sensor as per the distance controll the brightness of the led
// Name: Rohit Kumar
// Reg. No: 12110865
// Roll No: 10
// Define pins
const int trigPin = 5;
const int echoPin = 18;
const int ledPin = 2;
// Variables
long duration;
int distance;
int brightness;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set up the sensor and LED pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Map the distance to a brightness level (0 to 255)
brightness = map(distance, 0, 399, 255, 0);
brightness = constrain(brightness, 0, 255); // Ensure the brightness is within the valid range
// Set the brightness of the LED
analogWrite(ledPin, brightness);
// Delay before the next loop
delay(100);
}