Arduino Uno
Breadboard
HC-SR04 sensor
Wires
The ultrasonic sensor uses sonar to determine the distance to an object. Here’s what happens:
The transmitter (trig pin) sends a signal: a high-frequency sound.
When the signal finds an object, it is reflected and…
… the transmitter (echo pin) receives it.
The time between the transmission and reception of the signal allows us to calculate the distance to an object. This is possible because we know the sound’s velocity in the air.
distance = (travel time / 2) x speed of sound
speed of sound = 343 m/s = 0.0343 cm/µS
The travel time must be divided by 2, because the wave is sent, hit the object, and then returns back to the sensor.
Below is the code to show in the Arduino IDE serial monitor/plotter the distance between the sensor and the object detected.
First in the setup() function the Serial must be initialized using Serial.begin(9600). This is required to be able to send values to the Arduino IDE to be shown in the computer.
In this example a new function is going to be created. Its name is readUltrasonicDistance() but you can use any name. This function has a prefix int, which indicates what it return, which will be the distance in cm. To make the function possible to quickly use different pin, it receives 2 arguments, triggerPin and echoPin. The triggerPin is the pin which is connected to the Trig pin in the HC-SR04 sensor. The echoPin is connected to Echo pin. Those two arguments will be used in the code.
First it it must be sent a 10 µS pulse to the triggerPin. To do that first the pin must be LOW, wait a few µS (in this case it is 5 µS) and than change the pin back to HIGH during 10 µS and change the pin back to LOW. This at is called to trigger the sensor.
Secondly, we read the value from the echoPin, using the function pulseIn to read the time spent by the sound wave sent by the sensor. That time is saved in the variable duration.
Finally the distance is calculated using the formula described above and then it is returned using the return instruction.
In the loop() function the readUltrasonicDistance() function is called and its result is saved int the cm variable. Afterwards its value is sent to the computer using the Serial.println(cm). This is repeat every 200 milliseconds by using the delay(200).
To open the Serial Monitor just open the menu Tools > Serial Monitor. The same for the Serial Plotter, it is inside the menu Tools. If you want you can use shortcut keys Ctrl+Shift+M to open the Serial Monitor and the Ctrl+Shift+L to open the Serial Plotter.