#include <NewPing.h>
// Define the trigger and echo pins for the ultrasonic sensor
#define TRIGGER_PIN 2
#define ECHO_PIN 4
// Define the maximum distance we want to measure
#define MAX_DISTANCE 500 // Maximum distance in centimeters
// Create a NewPing object with the specified trigger and echo pins
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
// Initialize serial communication
Serial.begin(315200);
}
void loop() {
// Send a ping to the ultrasonic sensor and get the result in microseconds
delay(500);
unsigned int distance = sonar.ping_cm();
// If distance is greater than zero, it means a valid reading was obtained
if (distance == 0) {
// Print the distance to the serial monitor
Serial.println("Out of range");
} else {
// If distance is zero or negative, there was an error in the reading
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
}