Connect hc sr04 as a 3 pin ultrasonic sensor.
4 pin ultrasonic sensor arduino code.
Ping sensor this sketch reads a ping ultrasonic rangefinder and returns the distance to the closest object in range.
Hello instructables i have had some trouble with my cheap ultrasonic sensor hc sr04 and today i found a really easy solution.
To do this it sends a pulse to the sensor to initiate a reading then listens for a pulse to return.
Programming the ultrasonic sensor.
The ultrasonic sensor can t do the echolocation stuff on its own though so you will need to program it your self don t worry its not very difficult.
Open the arduino ide software on your computer.
Coding in the arduino language will control your circuit.
1 arduino uno r3.
Select the port i e com3 and choose your arduino board type i e arduino uno genuino then compile it to your arduino.
The code will get the pulse inpu and output it onto the serial monitor.
So it can run with the same arduino code used for a ping sensor.
A 4 pin hc sr04 need to be interfaced like a 3 pin sensor module for a 3 wire connection which shares the trigger and echo pins to operate in a single line.
Next i will explain to you how the code works.
There is a demo code attached in the code section.
Follow the circuit diagram and make the connections as shown in the image given below.
You can upload the following example code to your arduino using the arduino ide.
For example if the object is 20 cm away from the sensor and the speed of the sound is 340 m s or 0 034 cm µs the sound wave will need to travel about 588 microseconds.
It is a really simple edit of the normal 3pin code.
But what you will get from the echo pin will be double that number because the sound wave needs to travel forward and bounce backward so in order to get the distance in cm we need to multiply the received travel time value.
An hc sr04 module can operate through a single line as like a ping sensor.
I added the 4 int s to the beginning of the code so you can changes the arduino pins very easily.
Open a new sketch file by clicking new.
How would i need to change the code and wiring if i am using the 4 pin.
Now that you have wired up the sensor it is time to connect the arduino to the computer and upload some code.
1 ultrasonic sensor hc sr04 procedure.
Here is the code from the tutorial.