#include <Arduino.h>

// TRIG sends an ultrasonic pulse; ECHO receives a pulse whose width tells us the distance.
const uint8_t TRIG_PIN = 12;
const uint8_t ECHO_PIN = 11;

// Configure TRIG as an output, ECHO as an input, and Serial Monitor at 9600 baud.
void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  // Start with TRIG LOW so the next HIGH pulse has a clean edge.
  digitalWrite(TRIG_PIN, LOW);
  // Serial lets us print measurements to the computer.
  Serial.begin(9600);
  delay(1000);
}

// Start a short trigger pulse, measure the echo, and report distance.
void loop() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  // Hold TRIG HIGH for 10 microseconds to start a measurement.
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  // pulseIn() measures the ECHO HIGH time in microseconds; 30000UL is the timeout.
  const unsigned long echoUs = pulseIn(ECHO_PIN, HIGH, 30000UL);
  // If the timeout expires without a pulse, report no usable echo.
  if (echoUs == 0) {
    Serial.println("No echo within timeout");
  } else {
    // Divide the echo time by about 58 to estimate centimeters (out and back travel).
    Serial.print(echoUs / 58UL);
    Serial.println("cm");
  }
  delay(1000);
}
