const int minDistance = 10; // Minimum distance in cm
const int maxDistance = 40;
const int trigPin = 32;
const int echoPin = 33; // Maximum distance in cm
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pulse duration in microseconds
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
float distance_cm = (duration / 2) / 29.1;
// Map the distance to a percentage value
int percentage = map(distance_cm, minDistance, maxDistance, 0, 100);
// Ensure the percentage stays within the 0-100 range
percentage = constrain(percentage, 0, 100);
// Print the distance and percentage
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.print(" cm, Percentage: ");
Serial.print(percentage);
Serial.println("%");
// Delay for some time before the next reading
delay(500);
}