#define US_TRIG 13 #define US_ECHO 12 long distance_cm, echo_duration; void setup() { //Serial port Serial.begin(115200); //Ultra sonic pins pinMode(US_TRIG, OUTPUT); pinMode(US_ECHO, INPUT); } void loop() { // start measurment by a short high pulse of 10 microseconds length at the trig pin ... digitalWrite(US_TRIG,LOW); delayMicroseconds(2); digitalWrite(US_TRIG,HIGH); delayMicroseconds(10); digitalWrite(US_TRIG,LOW); // measure the duration in microseconds of the echo pin HIGH - this is the time the echo needs to be back at the sensor pinMode(US_ECHO,INPUT); echo_duration = pulseIn(US_ECHO,HIGH); // convert into cm ... 344m/sec is the speed of noise - thus 34400cm/sec ... or 34,400cm/milisec ... or 0,0344cm/microsec // the echo has to go the distance twice - forth and back - so the duration has to be the half of the measured one // distance_cm = echo_duration/2 * 0,0344 or distance_cm = echo_duration/2 / 29,1 distance_cm = (echo_duration/2) / 29.1; //print this result at the screen Serial.print("Distance in cm: "); Serial.println(distance_cm); //wait before next measurement delay(250); //ms }