// Include necessary libraries
#include <NewPing.h>
// Define ultrasonic sensor pins
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
// Create an instance of the NewPing library to handle the sensor
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 baud rate
}
void loop() {
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
unsigned int distance = sonar.ping_cm(); // Send ping, get distance in centimeters.
if (distance == 0) {
Serial.println("Error: No ping received.");
} else {
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
}