#include <NewPing.h>
#define TRIGGER_PIN 9 // Arduino pin connected to the sensors Trig pin
#define ECHO_PIN 10 // Arduino pin connected to the sensors Echo pin
#define MAX_DISTANCE 200 // Maximum distance (cm) we want to measure
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // Create a NewPing instance
void setup() {
Serial.begin(115200); // Start the serial communication at 115200 baud rate
}
void loop() {
delay(50); // Wait 50ms between pings for more accurace readings
int distance = sonar.ping_cm(); // Measure the distance in centimeters
if (distance > 0 && distance <= MAX_DISTANCE) { // Check if the measured distance is within range (0-200 cm)
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
} else {
Serial.println("Out of range");
}
delay(1000); // Wait 1 second before taking next measurement
}