You also You need these items
Ultrasonic Distance Sensor – HC-SR04
How ultrasonic module works
Basically, this module sends a 40000Hz ultrasonic sound then when the sound hits an object it will come back like the image after that the ultrasonic microphone will hear it and the module will give us the time the sound was sent and came back
After we got the time we can calculate the distance with the speed of the sound
now as you understand the basics lets go codding
How to connect
At first, you see a new thing culled long duration; what’s that ha ? can you guess ???
okay long is a type of int that you can store numbers in it confused? I know you say what’s the point then?
well the difference between them is the storage so int can store 16 bytes(2-byte) of data means -32,768 to 32,767 but long can Handel More its size is 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647
now we should set the pins in my code I’ve set the Tring pin to pin 3 that should be output and also Echo to pin 2 that is input so it means we send data to pin 3 and we get data from pin 2 easy
okay now let’s go to void loop
so at first we set the pin 3 to 0V then we wait for 2 Microseconds after that we make that pin 5V but now we wait for 10 microseconds and when the delays finish we make it 0V
wait why we are even doing this what is this
well, we are creating a square wave to set up the module
then we need to get the data but if you remember at first I told you it’s a pulse square wave so how we can measure that ha?
well there is a command called pulseIN(pin,trigger)
this command just gets the time of the trigger so in here we settled the trigger to 5V means it will calculate the calculate how much time the module send 5V
I promise the is the last one
after that, we just need to get the distance = duration * 0.034 / 2
this is the formula
and the next we show the results on the serial monitor