#define PIN_TRIG 16 #define PIN_ECHO 15 long duration, cm; void setup() { // Initialize communication on the serial port Serial.begin(9600); //Define inputs and outputs pinMode(PIN_TRIG, OUTPUT); pinMode(PIN_ECHO, INPUT); } void loop() { // First, we generate a short pulse with a duration of 2-5 microseconds. digitalWrite(PIN_TRIG, LOW); delayMicroseconds(5); digitalWrite(PIN_TRIG, HIGH); // With the signal high, wait about 10 microseconds. At this point, the sensor will send signals at a frequency of 40 kHz. delayMicroseconds(10); digitalWrite(PIN_TRIG, LOW); // The delay time of the acoustic signal on the echo sounder. duration = pulseIn(PIN_ECHO, HIGH); // Now it remains to convert time to distance cm = (duration / 2) / 29.1; if (cm > 400) { Serial.println("Distance was measured incorrectly"); } else { Serial.print("Distance to object: "); Serial.print(cm); Serial.println("cm."); } // Delay between measurements for the sketch to work correctly delay(250); }