#define TRIG_PIN 3 #define ECHO_PIN 4 void setup() { Serial.begin(9600); pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); } void loop() { long duration, distance; // Clear the TRIG_PIN digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2); // Send a pulse to TRIG_PIN digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // Measure the duration of the pulse received on ECHO_PIN duration = pulseIn(ECHO_PIN, HIGH); // Convert the duration into distance distance = (duration * 0.0343) / 2; // Print the distance to Serial Monitor Serial.print(distance); Serial.println(); delay(1000); // Wait for a second before taking the next measurement }