Echo Time to Centimetres
Part of the Displays and Sensors section of Coddy's Arduino journey. Lesson 19 of 24.
Sound travels about 0.034 centimetres every microsecond. Multiply the echo time by that and you get how far the sound went.
But the sound went to the object and back, so the object is half that far away:
float cm = duration * 0.034 / 2;At 1 metre the echo takes about 5800 microseconds: 5800 times 0.034 is 197 cm there and back, so 98.6 cm away. Write the 0.034 with its decimal point: the sum then keeps its decimals.
Expect a centimetre or two of error: air temperature changes the speed of sound, and this sensor reads a little short.
Challenge
EasyThe sketch prints the echo time. Print the distance instead:
- turn the time into centimetres: times 0.034, divided by 2
- print the centimetres instead of the time
Press Run, move the object, then Check.
Try it yourself
const int trigPin = 9;
const int echoPin = 10;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
// turn the echo time into centimetres and print that
Serial.println(duration);
delay(200);
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Displays and Sensors
1Seven-Segment Displays
Seven-Segment DisplayDigit Patterns in BytesCount on the DisplayCountdown to ZeroDice Roller4Sensors
Ultrasonic Echo TimeEcho Time to CentimetresThermistor TemperatureCelsius to FahrenheitLight Level BarDistance on the LCDLCD ThermometerPractice on your own: Arduino playground