// pin #'s to which the Range Sensor pins are connected. int triggerPin = 8; int echoPin = 9; // Called to initialize the Arduino on power up. void setup() { // Initialize the serial port to 115200 baud. All Serial.println() commands // will send their output to the serial port at this baudrate, and can be // seen by going to Tools->Serial Monitor Serial.begin( 115200 ); Serial.println( "Startup...\n" ); pinMode( triggerPin, OUTPUT ); pinMode( echoPin, INPUT ); } // Called repeatedly void loop() { // Set the trigger pin high for 10 Microseconds digitalWrite( triggerPin, 1 ); delayMicroseconds( 10 ); digitalWrite( triggerPin, 0 ); // Now watch for a "High" pulse on the echo pin. Time out if it takes more than // 1/4 second int duration = pulseIn( echoPin, HIGH, 250000 ); // Speed of sound is 343.2m/S or 34320cm/S, but pulse length is the time it takes // for the ultrasonic burst to travel to the object and back. Duration is measured // in microseconds (0.000001S) // distance = 34320cm/S * duration * 0.000001 / 2; // = 0.01716 // ~= 1/58 int distance = duration / 58; Serial.println( distance ); // wait 1/2 second before taking another measurement. delay( 500 ); }