const int TRIG_PIN = 12; // Pins const int ECHO_PIN = 11;const unsigned int MAX_DIST = 23200; // Anything over 400 cm (23200 us pulse) is "out of range"
void loop() { unsigned long t1, t2, pulse_width; float cmValue, inchesValue; digitalWrite(TRIG_PIN, HIGH); // Hold the trigger pin high for at least 10 us delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); while ( digitalRead(ECHO_PIN) == 0 ); // Wait for pulse on echo pin t1 = micros(); while ( digitalRead(ECHO_PIN) == 1); //end of echo t2 = micros(); pulse_width = t2 - t1; //calculate time between send pulse and returned pulse cmValue = pulse_width / 58.0; //convert time into cm inchesValue = pulse_width / 148.0; //convert time into inches if ( pulse_width > MAX_DIST ) { Serial.println("Out of range"); } else { Serial.print(cmValue); //print distance in cm Serial.print(" cm \t"); Serial.print(inchesValue); //print distance in inches Serial.println(" in"); } delay(60);}